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
Nov 27, 2024Technology
Stoicism At Work

This article explores how Stoic principles can be applied in the workplace to navigate stress, improve self-control, and focus on what truly matters, with practical examples from the author’s experience in software development.

Sep 21, 2020Technology
How to Optimize Django ORM Queries

Django ORM is a very abstract and flexible API. But if you do not know exactly how it works, you will likely end up with slow and heavy views, if you have not already. So, this article provides practical solutions to N+1 and high loading time issues. For clarity, I will create a simple view that demonstrates common ORM query problems and shows frequently used practices.

May 9, 2018Technology
How to Generate PDF Files in Python with Xhtml2pdf, WeasyPrint or Unoconv

Programmatic generation of PDF files is a frequent task when developing applications that can export reports, bills, or questionnaires. In this article, we will consider three common tools for creating PDFs, including their installation and converting principles.

Jan 28, 2017Technology
Creating a site preview like in slack (using aiohttp)

In this article we will write a small library for pulling metadata and creating a preview for a site just like Slack does.

Sep 22, 2016Technology
Angular Form Validation

In this article, we will describe some useful scripts and directives we use with angular form validation in our projects.

Jul 1, 2010Technology
Overriding QuerySet in Django

As you know, model managers can be overriden in Django. It's convenient to add custom filtration method.