voithos
voithos

Reputation: 70552

Tastypie: include computed field from a related model?

I've looked through Tastypie's documentation and searched for a while, but can't seem to find an answer to this.

Let's say that we've got two models: Student and Assignment, with a one-to-many relationship between them. The Assignment model includes an assignment_date field. Basically, I'd like to build an API using Tastypie that returns Student objects sorted by most recent assignment date. Whether the sorting is done on the server or in the client side doesn't matter - but wherever the sorting is done, the assignment_date is needed to sort by.

Idea #1: just return the assignments along with the students.

class StudentResource(ModelResource):
    assignments = fields.OneToManyField(
        AssignmentResource, 'assignments', full=True)

    class Meta:
        queryset = models.Student.objects.all()
        resource_name = 'student'

Unfortunately, each student may have tens or hundreds of assignments, so this is bloated and unnecessary.

Idea #2: augment the data during the dehydrate cycle.

class StudentResource(ModelResource):    
    class Meta:
        queryset = models.Student.objects.all()
        resource_name = 'student'

    def dehydrate(self, bundle):
        bundle.data['last_assignment_date'] = (models.Assignment
            .filter(student=bundle.data['id'])
            .order_by('assignment_date')[0].assignment_date)

This is not ideal, since it'll be performing a separate database roundtrip for each student record. It's also not very declarative, nor elegant.

So, is there a good way to get this kind of functionality with Tastypie? Or is there a better way to do what I'm trying to achieve?

Upvotes: 1

Views: 792

Answers (1)

msc
msc

Reputation: 3800

You can sort a ModelResource by a field name. Check out this part of the documentation http://django-tastypie.readthedocs.org/en/latest/resources.html#ordering

You could also set this ordering by default in the Model: https://docs.djangoproject.com/en/dev/ref/models/options/#ordering

Upvotes: 1

Related Questions