0

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.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
A.J.
  • 8,557
  • 11
  • 61
  • 89

1 Answers1

1

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:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Just moving on, I can use `COALESCE` with select extra, which gives me first non null value. is there any way to use the same in annotate functions? – A.J. Sep 02 '14 at 14:02
  • @Jack I think this can be a separate legitimate Stackoverflow question - more people could help you as opposed to using comments. Thank you. – alecxe Sep 02 '14 at 14:05