【问题标题】:Django Naturaltime is not working in .annotateDjango Naturaltime 在 .annotate 中不起作用
【发布时间】:2017-05-24 02:29:57
【问题描述】:

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

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。

【问题讨论】:

    标签: python django django-models django-annotate


    【解决方案1】:

    annotation 不能使用 naturaltime 函数,annotation 是在数据库级别完成的计算。

    Django 只提供了一组可以被数据库处理的基本计算,如Count, Sum, Min, Max 等。您可以参考official doc 了解更多关于Query Expressions 的信息。

    【讨论】:

    • 是的,我后来发现了它。我想我会按原样通过日期。我想我应该在前端使用moment.js 来做到这一点。
    • 您可以传递日期,然后在模板中使用naturaltimetimesince,无需在javascript 中使用。
    • 我只是在构建 REST Api。前端正在使用其他框架。所以..我想这是我能有的唯一解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    • 2011-11-04
    • 2018-06-10
    • 2021-01-30
    • 2017-10-24
    • 2019-09-05
    • 1970-01-01
    相关资源
    最近更新 更多