【问题标题】:In Django with Tastypie, can't get order_by to work with relation在带有 Tastypie 的 Django 中,无法让 order_by 使用关系
【发布时间】:2017-06-08 12:44:56
【问题描述】:

我正在使用 GET 和美味派来过滤结果,并且需要按日期字段对结果进行排序,但美味派抱怨该字段不允许排序。

Django version: 1.10.2
Tastypie version: 0.13.3

示例网址:

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

美味资源示例:

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']

回复:

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

【问题讨论】:

  • 您是否尝试将'bars__insp_date' 添加到FooResource 的订购列表中?
  • @makaveli 成功了。谢谢!

标签: django python-3.x tastypie


【解决方案1】:

正如我在 cmets 中所述,您必须添加与您正在使用的资源的模型相关的字段名称。因此,如果您想通过 BarModel 的字段对 FooModel 进行排序,则必须将关系指定为 'bar__field'。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 2012-10-04
    • 1970-01-01
    • 2013-01-27
    相关资源
    最近更新 更多