繁体   English   中英

Django Naturaltime无法在.annotate中工作

[英]Django Naturaltime is not working in .annotate

在这里,我只想注释一个模型上的字段,该字段提供人类可读的格式,说明自创建以来已花费了多少时间

My Model is created 30 seconds ago

我的型号说明:

from django.db import models 
class MyModel(models.Model):
    name = models.CharField(max_length=100)
    created_at = models.DateTimeField(auto_now_add=True)

class Meta:
    ordering = ['-created_at']

@property
def natural_time(self):
    return naturaltime(self.created_at)

我所做的就是在这里

from django.contrib.humanize.templatetags.humanize import naturaltime
from django.db.models import F
from .models import MyModel
m = MyModel.objects.annotate(timesincecreated=naturaltime(F('created_at'))
print m.values('timesincecreated')

在此打印调用中,我得到了模型中使用的DateTimeField 但是如果我要访问该属性。

from .models import MyModel
m= MyModel.objects.first()
print m.natural_time

有用。

有什么帮助吗? TIA。

您不能将naturaltime函数用于annotationannotation是在数据库级别完成的计算。

Django仅提供一组可以由数据库处理的基本计算,例如Count, Sum, Min, Max等。您可以参考官方文档以了解有关Query Expressions更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM