Cole
Cole

Reputation: 2509

Django customize model.Manager so it accepts arguments

I would like to be able to pass args or kwargs through objects if possible, and without needless complications. It would look something like Model.objects('something').all() or Model.objects('something').order_by('field'). I tried to customize __init__ for AManager, but couldn't get it to work, so it might be as simple as writing the appropriate __init__ function.

What I have done is add a method to a custom Manager, which looks something like this:

class AManager(models.Manager):
    def example(self, arg):
        self.example = arg
        return self

class A(models.Model):
    name = models.Charfield()

    objects = AManager()

In this example, A.objects.example('name').all() would return the usual A.objects.all(), unless of course, example('name') affects the QuerySet somehow. What I want to do is avoid something like A.objects.custom_filter('name').another_filter('name') where I have to include a duplicate arg for each chained filter.

Upvotes: 0

Views: 1382

Answers (1)

Kevin Stone
Kevin Stone

Reputation: 8981

You need to add a __call__ method to your manager which accepts this argument and returns a different query set then the default manager (or another manager based on the argument).

You're better off writing custom query set methods and returning them. Querysets are designed to be chained, so you shouldn't have to continue to pass the same argument.

If you add your specific use case, I can show you how to construct it using a custom Manager and/or QuerySet classes.

Upvotes: 1

Related Questions