Reusable Queries with Q

Sorry, don’t have the time at the moment to really digest your message, but there was one tiny part I can comment on right now:

The “**kwargs” mechanic passes a dictionary in as a set of keyword args and values.

So for example:

User.objects.filter(first_name='Ken', last_name='Whitesell')

is exactly the same as:

kwargs = {'first_name': 'Ken', 'last_name': 'Whitesell'}
User.objects.filter(**kwargs)

or even:
User.objects.filter(**{'first_name': 'Ken', 'last_name': 'Whitesell'})

Keeping that equivalence in mind allows you to dynamically create any query or set of Q objects to build arbitrary queries on the fly.

3 Likes