Django: inspect queryset to get applied filters

8.8k views Asked by At

Is there a way to inspect a queryset and get info about which filters/exclude have been applied?

I need it for debugging: I cannot understand why my queryset excludes some data...

3

There are 3 answers

0
Yuji 'Tomita' Tomita On BEST ANSWER

That doesn't seem easy to do. Each filter is applied differently to the query object so you're not going to find a cleanly laid out "filter1", "filter2", "filter3".

Check out myqueryset.query.__dict__ - the incoming filter is separated into relevant areas immediately and no record stored. Details in django.db.models.sql.query.Query.

I'd check out the SQL instead.

print myqueryset.query 
0
eveiga On

If you are debugging in a shell:

from django.db import connection
print connection.queries

If you are making requests in a browser use django debug toolbar, it's a great tool and can be very helpful:

Django Debug Toolbar

0
asmatrk On

You can use also:

your_qs.query.where.children

or:

your_qs._has_filters().__dict__['children']

and to access to the first filter that you applied:

your_qs._has_filters().__dict__['children'][0].__dict__