Reputation: 1319
my model looks like this
class Model(models.Model):
user_id = models.ForeignKey()
date = models.DateField()
field1 = models.FloatField()
field2 = models.FloatField()
I have a below queryset
queryset = Model.objects.filter(user_id__exact=5) \
.annotate(weekstartdate=Trunc('date', 'week')) \
.values('weekstartdate') \
.annotate(avg_field1=Avg('field1')) \
.annotate(avg_field2=Avg('field2')) \
.order_by('-weekstartdate')
which is working perfectly. now I want to add weekenddate field to above queryset which has a date = weekstartdate + 6 days. I have added below line to above query
.annotate(weekenddate=Trunc('date', 'week') + timedelta(days=7), output_field=DateField())
but it is complaining :-
TypeError: QuerySet.annotate() received non-expression(s): <django.db.models.fields.DateField>
Relative imports
from django.db.models import Avg, Q
from django.db.models.functions import Trunc
from django.db.models import DateTimeField, ExpressionWrapper, F, DateField
Note :- Simple for loop after queryset is not i am looking for because after assigning manually a field, queryset filter is still fetching query from old queryset due to laziness of the queryset. If answer can be in relativedelta of dateutil library it would be much better.
Upvotes: 0
Views: 3455
Reputation: 6608
You need to use ExpressionWrapper
around it.
YourModel.objects.annotate(
weekenddate=models.ExpressionWrapper(
Trunc('date', 'week') + timedelta(days=7),
output_field=models.DateField(),
),
)
Upvotes: 1