【问题标题】:Django Many-To-One relationship filter setDjango 多对一关系过滤器集
【发布时间】:2015-08-08 19:44:46
【问题描述】:

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

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 django django-orm


    【解决方案1】:

    根据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

    【讨论】:

    • 这真的很接近我想要的。你的例子非常有帮助!一个问题是它似乎返回了在“这里”或“那里”有东西的组。我希望只有在设置了这两个组时才返回组。
    • 你让我在正确的方向上找到了足够的答案。这是我找到问题的最终解决方案的地方:stackoverflow.com/questions/8618068/…
    猜你喜欢
    • 2020-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-20
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    相关资源
    最近更新 更多