python - 查询集仅返回分配了外键的对象。Django

标签 python django django-queryset

我正在尝试找到一种简单的方法来返回相互分配了外键的对象。

例如,我有这样的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 创建对象family1family2family3。我为我的 child 创建了对象 JohnStefani,它们与 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/

相关文章:

django - 在 Django 中分组和排序

python - Web 应用程序的 Storm ORM 与 PyORMish

python - PyTorch DataLoader() 中的 next() 和 iter() 做了什么

reactjs - AWS Cognito 与 django 休息框架 react js?

python - 使用 AWS 部署 Django

python - 如何在 Django 中进行连接?

django - 在 Django 中按整数字段的内容搜索

python - Django 和枕头

python - 列表理解中的生成器表达式未按预期工作

python - 编写 Django 迁移,根据另一个字段添加一个唯一字段