Django:按功能添加新列( datetimefield 到 datefield )

Django: add new column by function ( datetimefield to datefield )

将日期时间字段更改为日期字段并放入新列

python ways are useless because i want to be able to use order_by and distinct
i don't want to use sorted() and etc

我的 django 模型是这样的

class Product(models.Model):
    price = models.PositiveIntegerField(null=False, default=0)
    discounted_price = models.PositiveIntegerField(null=False, default=0)
    date = models.DateTimeField(auto_now_add=True)

我希望能够调用 date() 函数
并将其放在另一列中 order_by it

Product.objects.annotate(day=date.date()).order_by('-day').distinct('day')

你可以这样做

Product.objects.annotate(date__date=date.date()).order_by('-date').distinct('date')

查看doc.了解更多信息

经过大量搜索,我找到了答案

from django.db.models.functions import TruncDate

Product.objects.annotate(day=TruncDate('date')).order_by('-day').distinct('day')