Django多对一关系过滤器集 - python

我有几个这样的模型设置:

Group(models.Model):
    name = models.TextField(max_length=255)

Thing(models.Model):
    location = models.TextField(max_length=255)
    group = models.ForeignKey(Group)

这只是说明这种关系的一个示例,因此请原谅任何语法错误。

我的问题是,如何找到一组具有特定位置的组?我应该能够使用以下方法访问与组关联的事物:

Group.thing_set

对?那么,有什么方法可以根据thing_set中的项目进行过滤?我在想一些类似的事情。

Group.objects.filter(thing_set.location in ["Location A", "Location B"]).all()

希望这能使我回到包含位置A和位置B的所有组中。任何建议或朝正确方向的推动都会非常有帮助!

谢谢。

python大神给出的解决方案

根据documentation,您必须使用模型名称作为查询运算符:

要引用“反向”关系,只需使用模型的小写字母即可。

models.py:

from django.db import models


class Group(models.Model):
   name = models.TextField(max_length=255)


class Thing(models.Model):
    location = models.TextField(max_length=255)
    group = models.ForeignKey(Group)

views.py:

from django.views.generic import ListView


class ReverseFK(ListView):
    model = Group

    def get_queryset(self):
        g = Group.objects.create(name="example")
        g.save()
        Thing.objects.create(location="here", group=g)
        return Group.objects.filter(thing__location__in=["here","there"])

Working code example on github