3

This question is a follow-up to the one here.

Suppose I have the following Django model:

from django.db import models
from django.db.models import 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'), 
                sum=Sum(F('my_date')+0)), #THIS NEEDS TO CHANGE. TO WHAT??
            )
        )

Instead of calculating the Sum of my_date, I would like to calculate the sum of the MySQL expression UNIX_TIMESTAMP('my_date'). How can I modify the Django QuerySet above to accomplish that?

Note: this question not a duplicate of this one because I am asking how to get this value from a QuerySet (IE: How do I get the Database to return this value). In that question, there is no Database. It is straight non-Django python. I'm using Django.

1 Answer 1

4

Look at func-expressions

from django.db.models import Func, F, Sum

queryset.annotate(sum=Sum(Func(F('my_date'), function='UNIX_TIMESTAMP')))
Sign up to request clarification or add additional context in comments.

1 Comment

I know this question was tagged MySQL, but for anyone else looking for a Postgres solution to the same problem, there is a good solution here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.