python - 如何筛选相关对象中的字段?

标签 python django django-models tastypie

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

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

返回“在‘玩家’字段中的查找不允许超过一层。”本质上,我正在尝试做我目前可以在 Django shell 中做的事情:

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

我正在使用以下代码,为简洁起见我对其进行了简化:

# 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 在字段“用户名”上定义了一个过滤器,所以这应该有效,但实际上无效。我什至尝试将“players__username”添加到 RoundResource 中的过滤器,但这也不起作用。

我读到了 basic filtering in the docs并查看了 GitHub 上的代码,但似乎没有任何内容。我还查看了 advanced filtering documentation它似乎不适合我的用例。我查看了 GitHub 上的 Tastypie 代码,但对它的理解还不够,无法确定 1) 我做错了,还是 2) 要重写什么才能使其正常工作。

最佳答案

显然,您需要在 filtering 行中专门将关系跨越查找列入白名单,如下所示:

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

至少,我认为这是放置它的正确位置。 relevant docs在例子上相当 slim 。不过,Tastypie 门票 suggests this should work .

关于python - 如何筛选相关对象中的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11905206/

相关文章:

python - 使用列表推导式对数据帧列表中的数据帧进行编号

python - 如何在自定义 handler500 中获取异常?

json - Django REST Framework 批量 PUT(更新)

mysql - 重命名 Django 模型及其对应的 MySQL 表

mysql - django queryset union 不能只使用

Django South "myapp.foo"已存在“初始迁移错误

django - 如何更改查询的默认顺序?

python - 如何将反斜杠转义序列放入 f-string

python - 从操作中排除列而不删除它

python - Django - 格式化/访问模板中的 Pandas.to_dict() 数据框