Can this django query be improved?
Posted
by Hobhouse
on Stack Overflow
See other posts from Stack Overflow
or by Hobhouse
Published on 2010-05-16T11:58:26Z
Indexed on
2010/05/16
12:00 UTC
Read the original article
Hit count: 245
Given a model structure like this:
class Book(models.Model):
user = models.ForeignKey(User)
class Readingdate(models.Model):
book = models.ForeignKey(Book)
date = models.DateField()
One book may have several readingdates.
How do I list books having at least one readingdate within a specific year?
I can do this:
from_date = datetime.date(2010,1,1)
to_date = datetime.date(2010,12,31)
book_ids = Readingdate.objects\
.filter(date__range=(from_date,to_date))\
.values_list('book_id', flat=True)
books_read_2010 = Book.objects.filter(id__in=book_ids)
Is it possible to do this with one queryset, or is this the best way?
© Stack Overflow or respective owner