Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Django, can you add a method to querysets?

In Django, if I have a model class, e.g.

from django.db import models  class Transaction(models.Model):     ... 

then if I want to add methods to the model, to store e.g. reasonably complex filters, I can add a custom model manager, e.g.

class TransactionManager(models.Manager):      def reasonably_complex_filter(self):         return self.get_query_set().filter(...)   class Transaction(models.Model):     objects = TransactionManager() 

And then I can do:

>>> Transaction.objects.reasonably_complex_filter() 

Is there any way I can add a custom method that can be chained to the end of a query set from the model?

i.e. add the custom method in such a way that I can do this:

>>> Transaction.objects.filter(...).reasonably_complex_filter() 
like image 970
Paul D. Waite Avatar asked Jan 02 '11 01:01

Paul D. Waite


People also ask

What are QuerySets in Django?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

What does _SET do in Django?

The _set is a reverse lookup class variable django puts in for you. The reason the reverse is a queryset is, ForeignKey is 1-to-many relationship. Hence, the reverse is a queryset. The _set object is made available when related_name is not specified.


1 Answers

As of django 1.7, the ability to use a query set as a manager was added:

class PersonQuerySet(models.QuerySet):     def authors(self):         return self.filter(role='A')      def editors(self):         return self.filter(role='E')  class Person(models.Model):     first_name = models.CharField(max_length=50)     last_name = models.CharField(max_length=50)     role = models.CharField(max_length=1, choices=(('A', _('Author')),                                                    ('E', _('Editor'))))     people = PersonQuerySet.as_manager() 

Resulting the following:

Person.people.authors(last_name='Dahl') 

In addition, the ability to add custom lookups was also added.

like image 154
Burhan Khalid Avatar answered Sep 21 '22 02:09

Burhan Khalid