Can this Django request be improved?

For a model structure like this:

class Book(models.Model):
    user = models.ForeignKey(User)

class Readingdate(models.Model):
    book = models.ForeignKey(Book)
    date = models.DateField()

There can be several Readingdates in one book .

How do I list books that have at least one Readingdatein a given year?

I can do it:

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 a query alone , or is this the best way?

+3
source share
1 answer
Book.objects.filter(readingdate__date__year=2010)
+5
source

Source: https://habr.com/ru/post/1745627/


All Articles