Fahim Ahmed
Fahim Ahmed

Reputation: 407

Compare returned difference of fields with a variable in django queryset

I am trying to list all objects of a model based on the difference of field values and a variable. For example I am trying to pull objects which has been created since 3 days or more. So I am trying to query the models as follows

import datetime
from myapp_books.models import Book
from django.db.models import F

current_date = datetime.date.today()
books = Book.objects.annotate(day_difference=F('date_added__date') - current_date).filter(day_difference__gte=3)
books.count()

This is giving me an error when I run it in the shell as follows

AttributeError: 'ExpressionNode' object has no attribute 'lookup'

Please advice. I am using django 1.5.12

Upvotes: 0

Views: 529

Answers (1)

Sayse
Sayse

Reputation: 43300

I don't think you need the annotation at all, you should just be able to filter on the date added that is older than 3 days old

Book.objects.filter(date_added__date__gte=datetime.now()-timedelta(days=3))

Also, you should upgrade to a supported version of django

Upvotes: 4

Related Questions