How to write Django QuerySet to get UNIX_TIMESTAMP of a DateTimeField?

Question:

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.

Asked By: Saqib Ali

||

Answers:

Look at func-expressions

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

queryset.annotate(sum=Sum(Func(F('my_date'), function='UNIX_TIMESTAMP')))
Answered By: madzohan
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.