A.J.
A.J.

Reputation: 8985

Django ORM: wrapper for model objects

I am looking for some way to define some wrapper that is called before i call to Model.objects.all().

I want whenever i call, Model.objects it call my method (wrapper) and then return the objects back to the query.

Lets take an example:

MyModel.objcts.filter(name="Jack")

Wrapper:

def mymodelWrapper(self):
    return self.objects.annotate(size=Sum('id', field='order_size_weight*requested_selling_price'))

I want to run annotate in the background and also want to apply the filter. I Know what i want to achieve, its the code i am looking for how to do that.

Upvotes: 0

Views: 2722

Answers (1)

alecxe
alecxe

Reputation: 473863

What you are talking about is perfectly doable with Django by using a custom model manager:

class MyModelManager(models.Manager):
    def get_query_set(self):
        return super(MyModelManager, self).get_query_set().annotate(size=Sum('id', field='order_size_weight*requested_selling_price'))


class MyModel(models.Model):
    objects = MyModelManager()

    # fields

Also see other similar topics:

Upvotes: 1

Related Questions