如何过滤相关对象中的字段? [英] How do I filter on a field in a related object?

查看:163
本文介绍了如何过滤相关对象中的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我尝试过滤相关对象中的某个字段,则Tastypie会返回一个错误。例如,运行

If I try to filter on a field in a related object then Tastypie returns an error. For example, running

curl -H "Accept: application/json" \
     "http://localhost:8080/wordgame/api/v1/rounds/?format=json&players__username=moe"

玩家领域的查询不允许超过一级。本质上,我正在尝试在Django shell中执行以下操作:

returns "Lookups are not allowed more than one level deep on the 'players' field." Essentially, I am trying to do what I can currently do in the Django shell:

Round.objects.all().filter(players__username=moe.username)

我正在使用以下代码,简化为简化: / p>

I am using the following code, which I simplified for brevity:

# wordgame/api.py which has tastypie resources
class RoundResource(ModelResource):
    players = fields.ManyToManyField(UserResource, 'players',full=True)
    . . .

    class Meta:
        queryset = Round.objects.all()
        resource_name = 'rounds'
        filtering = {
            'players': ALL,
        }

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'players'
        filtering = {
            'username': ALL,
        }

# wordgame/models.py which has Django models
class Round(models.Model):
    players = models.ManyToManyField(User)
    word = models.CharField(max_length=75)
    . . . 

我假设因为UserResource在字段用户名上定义了这个应用程序的过滤器它不是。我甚至尝试在RoundResource中的过滤器中添加players__username,但是这也不行。

I'm assuming that because UserResource defines a filter on the field 'username' that this should work but it does not. I even attempted to add "players__username" to the filter in RoundResource, however this did not work either.

我阅读了关于基本过滤在文档中,并查看了GitHub上的代码,但是似乎并没有什么。我还看了一下高级过滤文档,它似乎不是以适应我的用例。我已经看过GitHub上的Tastypie代码,但是不明白它是否足以弄清楚1)我这样做是错误的,或者2)要覆盖这个工作。

I read about basic filtering in the docs and looked at the code on GitHub however there doesn't seem to be anything for this. I also took a look at the advanced filtering documentation and it doesn't seem to fit my use case. I've looked at the Tastypie code on GitHub but don't understand it enough to figure out if 1) I am doing this wrong, or 2) what to override to get this to work.

推荐答案

显然,您需要在过滤行中明确列出关系跨越查找,就像这样:

$ b

Apparently, you need to specifically white-list the relation-spanning lookups in your filtering line, like this:

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'players'
        filtering = {
            'username': ALL_WITH_RELATIONS,
        }

至少,我认为是正确的地方。 相关文档在实例上相当渺茫。然而,一个Tastypie门票,建议这应该工作

At least, I think that's the right place to put it. The relevant docs are fairly slim on examples. A Tastypie ticket, though, suggests this should work.

这篇关于如何过滤相关对象中的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆