是否可以测试单个模型实例是否满足Q对象的条件?
那么,是否有类似is_q_satisified
的函数:
article = Article.objects.filter(title='Foo')[0]
q = Q(title='Foo')
assert is_q_satisfied(q, article)
答案 0 :(得分:4)
没有内置is_q_satisified
,但你可以通过过滤q和对象的主键来自己创建一个。
# Note I've used get() to return an object,
# instead of filter(), which returns a queryset.
article = Article.objects.filter(title='Foo')
def is_q_satisfied(obj, q):
return type(obj).objects.filter(q).filter(pk=obj.pk).exists()
q = Q(title='Foo')
is_q_satisfied(article, q)