Django Custom Queryset vs Custom Manager for Database queries

Note: this applies to Django >= 1.7

From the docs:

A Manager is the interface through which database query operations are provided to Django models. At least one Manager exists for every model in a Django application.

There are two reasons you might want to customize a Manager: to add extra Manager methods, and/or to modify the initial QuerySet the Manager returns.

Since Django 1.7 and onwards, we no longer need to create custom manager and custom queryset separately. We can turn custom queryset into manager like so.
objects = EcomProductQuerySet.as_manager()

Custom Queryset is a way to simplify the database queries. For example if we have a database model like so:

Here, I could have used EcomProduct.objects.filter(featutred=True) to get only the featured products. Instead, we created a method in custom queryset called featured. Now we can get the featured products like so:
EcomProduct.objects.featured(). This might be a trivial example, but this concept really makes a difference in larger queries.

Query Chaining

Another excellent feature of a queryset is its ability to chain. An example of it is here. In the listview, we create a queryset that only shows “featured” items AMONGST “active” items. These chains can be arbitrarily long.

Note that we could have made this particular query like so (without any custom querysets), but using these custom querysets makes our queries look more DRY and cleaner.




No Comments


You can leave the first : )



Leave a Reply

Your email address will not be published. Required fields are marked *