我有这个django代码
Build->Build APK
当我尝试
时CreateMap<Source, Dest>(MemberList.Source)
我得到结果
q1 = MyModel.objects.all()
q2 = MyModel.objects.all()
那么如何检查django中的两个查询集结果是否等于?
答案 0 :(得分:4)
您可以将查询集转换为列表并检查它们是否相等:
q1 = Model.objects.all()
q2 = Model.objects.all()
equal = True
for idx, q in q1:
if q != q2[idx]:
equal = False
print(equal)
答案 1 :(得分:1)
尝试一下:
q1.intersection(q2).count() == q1.count() and q1.count() == q2.count()
答案 2 :(得分:1)
您可以将其转换为集合,以检查2个查询集合是否具有相同的元素(尽管有序)。
set(lit(q1)) == set(list(q1))
它将返回:
True
答案 3 :(得分:0)
我花了2美分作为一个函数,该函数比较两个QuerySet是否相等,而忽略排序顺序。注意,我实际上并没有检查QuerySet是否为空。我会留给你。
def querysets_are_same(qs1, qs2, exclude_fields=[]):
'''
Check whether two queryset have the same content, sort order of querysets is ignored.
Params:
-------
qs1 (QuerySet) - first queryset to compare
qs2 (QuerySet) - second queryset to compare
exclude_fields (list) - fields to exclude from comparison; primary key field is automatically removed.
Yield:
------
True if both querysets contain the same data while ignoring sort order; False otherwise
'''
# lookup primary key field name
pk_qs1 = qs1[0]._meta.pk.name
pk_qs2 = qs2[0]._meta.pk.name
# update excluded fields
exclude_fields_qs1 = set(exclude_fields) | set([pk_qs1])
exclude_fields_qs2 = set(exclude_fields) | set([pk_qs2])
# convert queryset to list of dicts excluding fields
list_qs1 = [{k:v for k,v in d.items() if not k in exclude_fields_qs1} for d in qs1.values()]
list_qs2 = [{k:v for k,v in d.items() if not k in exclude_fields_qs2} for d in qs2.values()]
# sort lists
list_qs1_sorted = sorted(sorted(d.items()) for d in list_qs1)
list_qs2_sorted = sorted(sorted(d.items()) for d in list_qs2)
return list_qs1_sorted == list_qs2_sorted
答案 4 :(得分:-2)
您可以通过.count()或:
查看size