每个月的最新条目

时间:2016-10-09 23:12:22

标签: mysql django

我有一个带有time_stamp(DateTime字段)的模型,我想获得每个月的最新条目。

我该如何解决这个问题?

型号:

class Transaction (models.Model):
    transaction_id = models.AutoField(primary_key=True)
    net_monthly_transaction = models.DecimalField(max_digits = 10, decimal_places = 2, default=0)
    # deposit or withdrawal (withdrawal with negative value)
    amount = models.DecimalField(max_digits = 10, decimal_places = 2)
    time_stamp = models.DateTimeField(default=datetime.now, blank=True)


    def __str__(self):              # __unicode__ on Python 2
        return str(self.time_stamp)  + str(self.amount) + str(self.net_monthly_transaction)

这很容易在我熟悉的mysql中完成,并且在SO中有很多答案,这里有一个例子:

SELECT * FROM table 
WHERE created_on in 
(select DISTINCT max(created_on) from table 
GROUP BY YEAR(created_on), MONTH(created_on))

Get last record of each month in MySQL....?

如何在Django中完成此操作?任何帮助或指示将不胜感激。

提前致谢,

1 个答案:

答案 0 :(得分:1)

您可以尝试以下代码。

from django.db import connection

truncate_date = connection.ops.date_trunc_sql('month', 'time_stamp')
report = Transaction.objects.extra({'month':truncate_date}).values('month').annotate(last_record=Max('time_stamp'))