我正在尝试找到一种简单的方法来返回相互分配了外键的对象。
例如,我有这样的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)
为我的 parent 创建对象family1
、family2
、family3
。我为我的 child 创建了对象 John
和 Stefani
,它们与 family1
中的外键相关。
创建仅返回family1
(仅一次,即使它有许多相关对象)的查询集的最简单方法是什么。返回family 1
,因为仅此对象存在ForeignKey。
最佳答案
您添加 .distinct()
call [Django-doc]在查询集的末尾。例如,如果您希望所有 Parent
都至少有一个 child ,您可以这样写:
# Parents that have at least one child
Parent.objects.filter(children__isnull=False)<b>.distinct()</b>
或者,如果您想查找名称以 Ste
开头的 child 的 Parent
,那么您可以查询:
# Parents that have at least one child with a name that starts with "Ste"
Parent.objects.filter(children__name__startswith='Ste')<b>.distinct()</b>
关于python - 查询集仅返回分配了外键的对象。Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57493801/