HenryM
HenryM

Reputation: 5793

DRY Django querysets

I have a query which users order_by on a number of aggregated fields in a database, like so:

list = MyList.objects.filter(key_item=None).extra(
        select={"diff":"abs(field1+field2+field3+field4+field5+field6+field7+field8+field9+field10)"}).order_by('-diff')

I'm using this is several places within my code and I'd rather have it in some centralized place.

I was wondering the best way in django to reuse this.

Upvotes: 1

Views: 249

Answers (1)

Alvaro
Alvaro

Reputation: 12037

You can add a manager to your model class to include that as a base filter. For example:

class MyListManager(models.Manager):
    def select_diff(self):
        return self.get_queryset().extra(...)


class MyList(models.Model):
    objects = MyListManager()

With this you can simply do:

MyList.objects.select_diff().filter(...)

You can find more about managers here

One big advantage of doing this over having the queryset written down somewhere is that you can still chain the queryset with additional filters / parameters and you comply with the django standard

Upvotes: 4

Related Questions