Reputation: 12585
This question is a follow-up to this one.
I'm running a Django application on top of a MySQL (actually MariaDB) database.
My Django Model looks like this:
from django.db import models
from django.db.models import Count, Sum
class myModel(models.Model):
my_string = models.CharField(max_length=32,)
my_date = models.DateTimeField()
@staticmethod
def get_stats():
logger.info(myModel.objects.values('my_string').annotate(
count=Count("my_string"),
sum1=Sum('my_date'),
sum2=Sum(# WHAT GOES HERE?? #),
)
)
When I call get_stats
, it gives me the count and the sum1.
However, for sum2
, I want the sum of the following Database expression for each matching row: my_date + 0
(this converts it to a true integer value).
What should I put in the expression above to get that sum returned in sum2
?
When I change it to sum2=Sum(F('my_date'))
, I get the following exception: http://gist.github.com/saqib-zmi/50bf572a972bae5d2871
Upvotes: 0
Views: 82
Reputation: 11808
Not sure, but try F() expression
from datetime import timedelta
myModel.objects.annotate(
count=Count("my_string"),
sum1=Sum('my_date'),
sum2=Sum(F('my_date') + timedelta(days=1))
).values('my_string', 'count', 'sum1', 'sum2')
https://docs.djangoproject.com/en/dev/ref/models/queries/#f-expressions
Upvotes: 1