[英]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
函數用於annotation
, annotation
是在數據庫級別完成的計算。
Django僅提供一組可以由數據庫處理的基本計算,例如Count, Sum, Min, Max
等。您可以參考官方文檔以了解有關Query Expressions
更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.