我试图找到一种简单的方法来返回具有彼此分配了外键的对象。
例如,我有这样的models.py文件:
class Parent(models.Model):
name = models.CharField(max_length=100)
class Children(models.Model):
parent = models.ForeignKey(Parent, on_delete=models.CASCADE)
name = models.CharField(max_length=10)
对于我的父母,我创建对象
family1
,family2
,family3
。我为我的孩子创建了与John
中的外键相关的对象Stefani
和family1
。创建仅返回
family1
(即使包含许多相关对象,也仅返回一次)的查询集的最简单方法是什么。返回family 1
,因为仅此对象存在ForeignKey。 最佳答案
您在查询集的末尾添加.distinct()
call [Django-doc]。例如,如果要所有具有至少一个孩子的Parent
,可以编写:
# Parents that have at least one child
Parent.objects.filter(children__isnull=False).distinct()
或者,如果要查找具有以
Parent
开头的名称的子对象的Ste
,则可以查询:# Parents that have at least one child with a name that starts with "Ste"
Parent.objects.filter(children__name__startswith='Ste').distinct()
关于python - Queryset仅返回分配了外键的对象。,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57493801/