And Condition Django Query Using Same Keyword

jac300 picture jac300 · May 31, 2013 · Viewed 8.2k times · Source

I have a Django application with a Publication model and a Tag model. Each publication has one or more Tags associated with it. I want to query the database with a set of two Tags and have returned only publications that have BOTH of those tags.

I cannot seem to find the syntax for this although I am certain it is readily available - I suppose I am not using the correct language to search. What I have tried already is:

pubs_for_tags = Publication.objects.filter(tags__title__istartswith=q, tags__title__istartswith=q2)

But this gives me an error "keyword argument repeated". I've also tried some variations of this, but nothing has worked so far. Can someone enlighten me on the correct syntax for this?

Answer

nnmware picture nnmware · May 31, 2013
pubs_for_tags = Publication.objects.filter(tags__title__istartswith=q).filter( tags__title__istartswith=q2)


or

pubs_for_tags = Publication.objects.filter(Q(tags__title__istartswith=q), Q( tags__title__istartswith=q2))