Django:查询所有具有外键指向的项目 [英] Django: query all items that have a foreign key point to them
问题描述
我有两个模型:
class A(models.Model):
name = models.CharField(max_length=100, unique=True)
class B(models.Model):
a = models.ForeignKey(A)
在Django中,我如何选择所有具有指向对象的 B类对象的 A类对象?例如,如果数据库包含 A类的以下三个条目:
In Django, how can I select all objects of class 'A' that have an object of class B that points to them? For example, if the database contains these three entries of class 'A':
A, named "one"
A, named "two"
A, named "three"
B:
B, points to "two"
B, points to "three"
我要选择类型A的两个和三个类。
I want to select classes "two" and "three" of type A.
推荐答案
您可以这样做:
a_qs = A.objects.filter(b = b)
其中b是 B类的对象
和 b =
表示要查询反向关系的小写模型名称。
where b is an object of class B
and the b=
refers to the lowercase model name which you want to query the reverse relationship.
有关在此处跨越关系的查找。它涵盖了如何对模型的ForeignKey属性进行反向查找
Read more on lookups that span relationships here. It covers how to do a reverse lookup on models' ForeignKey attributes
编辑:
如果您正在寻找所有没有的对象都指向任何 ForeignKey
对象,可以使用 排除
和 __ isnull
If you are looking for all objects which do not have any ForeignKey
objects pointing to them, you can use exclude
and __isnull
a_qs = A.objects.exclude(b__isnull = True)
这篇关于Django:查询所有具有外键指向的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!