开发者

Can this Django query be improved?

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?


Book.objects.filter(readingdate__date__year=2010)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜