views:

286

answers:

1

Hi! I have to work with a queryset, that is already filtered, eg. qs = queryset.filter(language='de') but in some further operation i need to undo some of the already applied filtering, eg not to take only the rows with language='de' but entries in all languages. Is there a way to apply filter again and have the new parameters connected to the already existing ones using OR not add, eg. if the queryset is already filtered for language='de' and i would be able to connect an 'OR language='en' to that, it would give me what i'm looking for! Thanks!

+1  A: 

I don't believe it is possible to do what you are asking.

The way you do ORs in django is like this:

Model.objects.filter(Q(question__startswith='Who') | Q(question__startswith='What'))

so if you actually wanted to do this:

Model.objects.filter(Q(language='de') | Q(language='en'))

you would need to put them both in the same filter() call so you wouldn't be able to add the other or clause in a later filter() call.

I think the reason you may be trying to do this would be that you are concerned about hitting the database again but the only way to get accurate results would be to hit the database again.

If you are simply concerned about producing clean, DRY code, you can put all the filters that are common to both queries at the top and then "fork" that query set later, like this:

shared_qs = Model.objects.filter(active=True)
german_entries = shared_qs.filter(language='de')
german_and_english = shared_qs.filter(Q(language='de') | Q(language='en'))
sheats
well this is what i thought too, that i can make "Or" queries in one filter using Q! Just wanted to know if there might be another possibility! Thanks!
lazerscience
It doesn't look like you are, but if you're using m2m relationships, go read the docs on those carefully, they're tricky: http://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships
Paul McMillan