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
Jul 13, 2022Technology
Prosemirror: Render node as react component

In this article I’m going to show how to declare custom prosemirror node, how to render it with toDom method and how improve that with custom NodeView using React component.

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.

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.

Mar 3, 2017Technology
Flask vs Django. Which Is Better for Your Web App?

There are two most popular web frameworks in Python. There is the Django with lots of intelligent defaults and the Flask micro framework with complete freedom in the choice of modules. Let’s see, what django vs flask is in 2017.

Oct 3, 2016Technology
How to include JQuery plugins in Angular 2 running via webpack

Learn more about how to include jquery plugins in angular 2 running via webpack. Our tutorial is perfect for Angular beginners.

Feb 18, 2010Technology
Absolute urls in models

Everybody knows about permalink, but it's usually used only in get_absolute_url. I prefer to use it for all related model urls.class Event(models.Model):# ...@models.permalinkdef edit_url(self):return ('event_edit', (self.pk, ))And then in template:<a href="{{ event.edit_url }}">Редактировать событие</a>