DEV Community

Discussion on: Optimize the Django ORM

Collapse
 
adamghill profile image
Adam Hill

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)