Back
Sep 23, 2010

Dynamic class generation, QuerySetManager and use_for_related_fields

It appears that not everyone knows that in python you can create classes dynamically without metaclasses. I'll show an example of how to do it.

So we've learned how to use custom QuerySet to chain requests:

Article.objects.old().public()

Now we need to make it work for related objects:

user.articles.old().public()

This is done using use_for_related_fields, but it needs a little trick. Thing is that in django related managers are initialized without arguments, and our QuerySetManager takes argument - queryset class.

objects = QuerySetManager(MyQuerySet)

We have to update QuerySetManager in such a way, that will allow setting queryset as class field:

class QuerySetManager(models.Manager):
    use_for_related_fields = True
    queryset_class = QuerySet

    def get_query_set(self):
        return self.queryset_class(self.model, using=self._db)

    def __getattr__(self, key):
        return getattr(self.get_query_set(), key)

In order to use this manager, we have to create a sublcass and set queryset_class:

class MyManager(QuerySetManager):
    queryset_class = MyQuerySet

It's not fun to create such class every time. So we'll write a function that does it for us:

def queryset_manager(qs_class):
    class Manager(QuerySetManager):
        queryset_class = qs_class
    return Manager()

Now it's enough to write:

objects = queryset_manager(MyQuerySet)

Subscribe for the news and updates

More thoughts
Apr 27, 2022TechnologyBusiness
How to Choose the Best Javascript Framework: Comparison of the Top Javascript Frameworks

In our article, you will find the best JavaScript framework comparison so that you know for sure how to choose the right one for your project.

Aug 25, 2017Technology
How to Upload Files With Django

File upload works differently from simple form inputs, which can be somewhat troublesome for beginners. Here I'll show you how to handle uploads with ease.

Jan 12, 2017Technology
Making Custom Report Tables Using AngularJS and Django

In this article I will tell you how to create an interactive interface with a widely customized visual look and different filtering to view reports.

Jan 9, 2017Technology
How to Use GraphQL with Django

GraphQL is a very powerful library, which is not difficult to understand. GraphQL will help to write simple and clear REST API to suit every taste and meet any requirements.

Aug 31, 2016Technology
Angular vs React Comparison

In this article, we will compare two most popular JS Libraries (Angular vs React). Both of them were created by professionals and have been used in famous big projects.

Sep 23, 2010Technology
OR and AND without django.db.models.Q

Learn how to use "OR" and "AND" queries efficiently in Django without using database models Q. Enhance your query-building skills. Dive in now.