我有一个带有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中完成此操作?任何帮助或指示,将不胜感激。

提前致谢,

最佳答案

您可以尝试以下代码。

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

关于mysql - 每个月的最新条目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39949457/

10-11 22:44
查看更多