Django: remove a filter condition from a queryset

Don picture Don · Jan 14, 2011 · Viewed 8.4k times · Source

I have a third-party function which gives me a filtered queryset (e.g. records with 'valid'=True) but I want to remove a particular condition (e.g. to have all records, both valid and invalid).

Is there a way to remove a filter condition to an already-filtered queryset?

E.g.

only_valid = MyModel.objects.filter(valid=True)
all_records = only_valid.**remove_filter**('valid')

(I know that it would be better to define 'all_records' before 'only_valid', but this is just an example...)

Answer

ikostia picture ikostia · Jan 14, 2011

Although there is no official way to do this using filter notation, you may easily do it with Q-notation. For example, if you ensure that third-part function returns a Q object, not a filtered QuerySet, you may do the following:

q = ThirdParty()
q = q | Q(valid=False)

And the resulting SQL conditions will be joined using OR operator.