re: Optimize the Django ORM VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Nice post, I've recently been using Q-objects for sql, makes building dynamics queries a lot easier, for example : def foo(username='',option_1=...
 

Yep!

One additional trick that I haven't seen referenced many places is to use a dictionary for dynamic queries. This trick only works for ANDs, though. The dictionary should use the column name as the keyword, and the lookup as the dictionary value. Then, you can expand the dictionary into kwargs for the filter query with a double-splat (i.e. .filter(**{})).

A silly example, but at least it gives you the idea:

filters = {
    "author__name": "Edgar Allen Poe",
    "title__startswith": "The ",
}

poe_books_that_start_with_the = Book.objects.filter(**filters)
code of conduct - report abuse