Check Q objects on model instance

Is it possible to check whether an instance of one model satisfies the conditions of the object Q? So is there a function like is_q_satisified:

article = Article.objects.filter(title='Foo')[0]
q = Q(title='Foo')
assert is_q_satisfied(q, article)
+4
source share
1 answer

There is no built-in is_q_satisified, but you can do it yourself by filtering on q and the primary key of the object.

# 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)
+4
source

Source: https://habr.com/ru/post/1609798/


All Articles