djangodjango-q

Test Q objects against model instance


Is it possible to test if a single model instance satisfies the conditions of a Q object? 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)

Solution

  • There isn't a built in is_q_satisified, but you can make one yourself, by filtering on the q and the object's primary key.

    # Note I've used get() to return an object, 
    # instead of filter(), which returns a queryset.
    article = Article.objects.get(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)