【发布时间】:2016-03-11 10:51:53
【问题描述】:
我有以下型号:
class Collection(models.Model):
...
class Record(models.Model):
collection = models.ForeignKey(Collection, related_name='records')
filename = models.CharField(max_length=256)
checksum = models.CharField(max_length=64)
class Meta:
unique_together = (('filename', 'collection'),)
我想执行以下查询:
对于Record 中的每个filename,我想知道Collections:
- 不要提供带有该文件名的
Record -
或提供这样的
Record但有不同的checksum
我想到了这样的输出:
| C1 C2 C3 <- collections
-----------+------------
file-1.txt | x
file-2.txt | x
file-3.txt | ! ! !
file-4.txt | x ! !
file-5.txt | ! ! x
x = missing
! = different checksum
到目前为止,我为每个 Collection 创建了一个查询,不包括此集合中但存在于其他集合中的所有文件名。
for collection in collections:
other_collections = [c for c in collections if c is not collection]
results[collection] = qs.filter(collection__in=other_collections).exclude(
filename__in=qs.filter(
collection=collection
).values_list('filename', flat=True)
).order_by('filename').values_list('filename', flat=True)
这在一定程度上解决了我的问题的第一部分,但相当古怪,需要后处理才能达到我想要的格式。而且,更重要的是,它没有解决 checksum 比较问题。
是否可以在一个组合步骤中执行两个查询以获得上述格式的结果?
该解决方案不一定必须使用 QuerySet API,我也可以回退到原始 SQL。
【问题讨论】:
标签: sql postgresql django-orm