- Author:
- simon
- Posted:
- May 1, 2008
- Language:
- Python
- Version:
- .96
- Tags:
- orm manager queryset
- Score:
- 7 (after 9 ratings)
An easy way to add custom methods to the QuerySet used by a Django model. See simonwillison.net/2008/May/1/orm/ for an in-depth explanation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | from django.db import models
class QuerySetManager(models.Manager):
def get_query_set(self):
return self.model.QuerySet(self.model)
# Using it in a model:
from django.db.models.query import QuerySet
import datetime
class Entry(models.Model):
...
objects = QuerySetManager()
...
class QuerySet(QuerySet):
def on_date(self, date):
next = date + datetime.timedelta(days = 1)
return self.filter(
posted__gt = date,
posted__lt = next
)
# Now you can get entries on a specific day like so:
# Entry.objects.all().on_date(datetime.date.today())
|
More like this
- Serialize a model instance by chriswedgwood 1 week, 6 days ago
- Automatically setup raw_id_fields ForeignKey & OneToOneField by agusmakmun 9 months, 2 weeks ago
- Crispy Form by sourabhsinha396 10 months, 1 week ago
- ReadOnlySelect by mkoistinen 10 months, 2 weeks ago
- Verify events sent to your webhook endpoints by santos22 11 months, 2 weeks ago
Comments
This works for Entry.objects.filter().on_date(date) but not Entry.objects.on_date(date) as some may wish, for this add the following snippet to QuerySetManager.
`
`
#
In response to the above comment, I believe it can simple be written as:
...since the default attribute lookup will check self.class and superclasses.
#
I had to modify my manager to the following so I would not receive Pickle Errors.
#
Please login first before commenting.