如何编写Django QuerySet以获取DateTimeField的UNIX_TIMESTAMP? [英] How to write Django QuerySet to get UNIX_TIMESTAMP of a DateTimeField?

查看:179
本文介绍了如何编写Django QuerySet以获取DateTimeField的UNIX_TIMESTAMP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是对 这里

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

假设我有以下Django模型:

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??
            )
        )

而不是计算 my_date 的总和,我想计算MySQL表达式的总和 UNIX_TIMESTAMP('my_date')。请问如何修改Django QuerySet以达到上述目的?

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?

注意:这个问题不是重复的 这一个 ,因为我在问如何从QuerySet获取这个值(IE:How do我得到数据库返回此值)。在这个问题上,没有数据库。它是直的非Django python。我正在使用Django。

推荐答案

查看 func-expressions

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

queryset.annotate(sum=Sum(Func(F('my_date'), function='UNIX_TIMESTAMP')))

这篇关于如何编写Django QuerySet以获取DateTimeField的UNIX_TIMESTAMP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆