Sep 23, 2010

Dynamic class generation, QuerySetManager and use_for_related_fields

Vladimir Sidorenko
Vladimir Sidorenko


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:


Now we need to make it work for related objects:


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)

More thoughts

Oct 01, 2017Technology
RESTful API Design: Best Practices

We've collected some useful tips regarding REST aimed for beginner developers.

Vladimir Sidorenko
Vladimir Sidorenko
Feb 28, 2017Technology
How to write an API in Django

There is such a term as Remote Procedure Call (RPC). In other words, by using this technology, programs can call functions on remote computers. There are many ways to implement RPC.

Vladimir Kalyuzhny
Vladimir Kalyuzhny
May 10, 2018Technology
How to Build a Cloud-Based Leads Management System for Universities

Lead management is an important part of the marketing strategy of every company of any size. Besides automating various business processes, privately-held organizations should consider implementing an IT solution that would help them manage their leads. So, how should you make a web-based leads management system for a University in order to significantly increase sales?

Vladimir Sidorenko
Vladimir Sidorenko
Feb 28, 2017Technology
Passing pieces of markup to components in Angular 2 and problems with dynamic content

In this article we'll research how to pass custom markup to Angular components and how to create different types of dynamic components.

Anton Lysenkov
Anton Lysenkov