我有以下课程:
class Company(Model):
name = models.CharField(max_length=250)
class Group(Model):
name = models.CharField(max_length=250)
company = models.ForeignKey('Company', on_delete=models.CASCADE)
country = CountryField(default='US')
有些情况下,一家公司可以在一个国家/地区拥有多个集团。我想获取在各自国家/地区唯一的所有公司集团。
谢谢
答案 0 :(得分:1)
您可以使用 Exists()
subqueries 为 Company
创建一个不存在的子查询,同时排除 pk
的 Group
并过滤匹配 company
和 {{1 }}:
country
注意:如果您使用 Django < 3.0 的版本,则无法直接过滤 from django.db.models import Exists, OuterRef
# will refer outer query as OQ in below comments
# Subquery to find any matching row of a particular row excluding the specified row
subquery = Group.objects.filter(
company=OuterRef('company'), # companies matching the current row of OQ
country=OuterRef('country') # countries matching the current row of OQ
).exclude(pk=OuterRef('pk')) # exclude current row of OQ
# find groups for which no entry exists in subquery
groups = Group.objects.filter(~Exists(subquery))
子查询,您需要先对其进行注释:
Exists