I have had difficulty in finding an easy way to add common methods to
querysets and managers for multiple models in Django.

I solved the problem in my projects by defining a custom `Manager`
class which defines `use_for_related_fields = True` and also overrides
`__getattr__()` to look for queryset and manager methods on an inner
`QuerySet` class on the model class, similar to the inner `Admin`
class.

{{{
from django.db import models
from django.db.models import query
from turbia import models as turbia_models

class Client(models.Model):
        is_deleted = models.BooleanField(default=False)
        objects = turbia_models.Manager()

        class QuerySet:
                def not_deleted(self):
                        return self.filter(is_deleted=False)

class Brand(models.Model):
        client = models.ForeignKey(Client)
        is_deleted = models.BooleanField(default=False)
        objects = turbia_models.Manager()

        class QuerySet:
                def not_deleted(self):
                        return self.filter(client__is_deleted=False, 
is_deleted=False)
}}}

I use this custom manager on an abstract base model class that all my
models are derived from, so it becomes trivial to add manager and
queryset methods when defining a new model. I can also define an inner
`QuerySet` class that is a subclass of another models inner `QuerySet`
class, when there are common queryset methods.

I'm sure there are problems with my implementation and it may not be
flexible or general enough to be relevant here (especially regarding
multiple manager support), but I would love to see improved support
built into the core of Django that would allow methods to be added to
both the manager and queryset for a model, and shared between
different (but similar) models much more easily.

I agree with Russell and others that these methods should not be
defined directly on the model (with a decorator).

Cheers.
Tai.

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/django-developers?hl=en.

Reply via email to