【问题标题】:Query database in django using model procedure使用模型过程在 django 中查询数据库
【发布时间】:2020-10-09 15:37:18
【问题描述】:

我创建了一个模型,该模型的过程从模型返回天数差的字段中减去两个日期,例如:

class Example:
    earlierDate=models.DateField()
    laterDate=models.DateField()

    def day_diff(self):
        return (laterDate-earlierDate).days

是否可以查询包含day_diff过程的数据库?

in_views_query=Example.objects.filter(day_diff__gte=30)

当我使用这种 o 查询时,它告诉我没有字段 'day_diff'

问候

【问题讨论】:

标签: django django-models django-views


【解决方案1】:

您可以使用ExpressionWrapper 来实现这一点

from django.db.models import DateField, ExpressionWrapper, F

Example.objects.annotate(day_diff=ExpressionWrapper(
                F('laterDate') - F('earlierDate'), output_field=models.DateField()
))

Django 在文档中也有一个类似的例子。看看:https://docs.djangoproject.com/en/3.0/ref/models/expressions/#using-f-with-annotations

【讨论】:

    猜你喜欢
    • 2012-12-22
    • 1970-01-01
    • 2020-02-22
    • 2021-04-08
    • 2021-10-04
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    相关资源
    最近更新 更多