Search code examples
djangopython-3.xtastypie

In Django with Tastypie, can't get order_by to work with relation


I am using GET with tastypie to filter the results and need to order the results by a datefield, but tastypie is complaining that the field does not allow ordering.

Django version: 1.10.2
Tastypie version: 0.13.3

Example URL:

localhost:8000/foos/api/foos/?format=json?order_by=bars__insp_date

Example Tastypie Resources:

class BarResource(ModelResource):

    class Meta:
        queryset = Bar.objects.all().distinct()
        resource_name = 'bars'
        filtering = {
            'insp_date': ALL_WITH_RELATIONS,
        }
        allowed_methods = ['get']
        ordering = ['insp_date']


class FooResource(ModelResource):

    onlinereports = fields.ToManyField(
        BarResource,
        'bars',
        null=True,
        full=True,
    )

    class Meta:
        queryset = Foo.objects.all().distinct()
        resource_name = 'foos'
        filtering = {
            'bars': ALL_WITH_RELATIONS,
        }
        ordering = ['bars']

Response:

{
error: "The 'bars' field does not allow ordering."
}

Solution

  • As I stated in the comments, you have to add the field name in relation to the model which resource you are using. So if you want to order FooModel by a BarModel's field, the relationship has to be specified as 'bar__field'.