我有一个模特:
class Person(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=50)
如果我这样做:
all_queryset = Person.objects.all()
all_queryset.count() # --> 8
subset_queryset = Person.object.filter(name = 'John')
subset_queryset.count() # --> 1
假设我想将subset_queryset
附加到all_queryset
(甚至保持重复):
result_qs = all_queryset.union(subset_queryset)
result_qs.count() # STILL 8!
# or
all_queryset |= subset_queryset
all_queryset.count() # STILL 8!
从某种意义上说,它实际上是一个逻辑联合:如果它是更全局查询集的子集,它将保留全局。 (逻辑交点qith &
的相反)。
联合将获得一个可选参数all
,该参数还将包括重复的行django doc
result_qs = all_queryset.union(subset_queryset, all=True)