Django如何在Queryset中过滤对象

时间:2019-02-08 00:06:10

标签: django django-rest-framework

我知道在QuerySet中过滤项目的正常方法如下:

class GameAPIListView(ListAPIView):
    serializer_class = GameSerializer
    def get_queryset(self):
        data = Game.objects.filter(name="Football")
        return data

如果我有一个看起来像这样的模型怎么办:

{
    "category_id": {
        "parent_id": {
            "name": "Sports",
            "category_id": "bf14aab0-dc76-4145-a130-246784d1efc1",
            "parent_id": null
        },
        "name": "Football",
        "category_id": "b6e59886-e834-4612-abc7-c32bd0e2af35"
    },
    "name": "Play Football",
}

{
    "category_id": {
        "parent_id": {
            "name": "Sports",
            "category_id": "bf14aab0-dc76-4145-a130-246784d1efc1",
            "parent_id": null
        },
        "name": "Basketball",
        "category_id": "b6e59886-e834-4612-abc7-c32bd0e2af35"
    },
    "name": "Play Basketall",
}

{
    "category_id": {
        "parent_id": {
            "name": "Poker",
            "category_id": "bf14aab0-dc76-4145-a130-246784d1efc1",
            "parent_id": null
        },
        "name": "blackjack",
        "category_id": "b6e59886-e834-4612-abc7-c32bd0e2af35"
    },
    "name": "Play blackjack",
}

我想获得所有其parent_id为Sports的物品。在这种情况下,我将获得足球和篮球。

我尝试了

data = Game.objects.filter(category_id.parent_id.name = "Sports")

但是没有用。有人可以告诉我正确的方法吗?非常感谢!

1 个答案:

答案 0 :(得分:1)

如果添加模型代码,则可以获得更准确的答案。

为什么不尝试这个。

data = Game.objects.filter(category__parent__name = "Sports")