比较模型中所有DateField的日期与当前日期 [英] compare the date of all DateFields in a model to the current date

查看:142
本文介绍了比较模型中所有DateField的日期与当前日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的模型中有

class MyModel(models.model):
    field1 = models.ForignKey(AnotherModel)
    field2 = models.DateField(blank=True, null=True)
    field3 = models.DateField(blank=True, null=True)
    field4 = models.DateField(blank=True, null=True)
    field5 = models.DateField(blank=True, null=True)
    ...
    field10 = models.DateField(blank=True, null=True)

如果一天过去了,我想测试每个字段,因此我可以在模板是这样的:

i want to test for each field if the day is in the past, so i can use in my template something like that:

{% for field in context.datetime_fields %}
    {% if field.is_past %}
       <span class="past">{{ field}}</span>
    {% else %}
        <span class="active">{{ field}}</span>
    {% endif %}
{% endfor %}

我发现了一些其他类似的问题,只是关于如何将一个DateField与当前日期进行比较。我要问的是如何遍历MyModel中的每个DateField并将每个字段与当前日期进行比较?

i found some other similar questions but all about how to compare one DateField with the current date. what i am asking is how to iterate over every DateField in MyModel and compare each field to the current date ?

推荐答案

类似。在我们的代码中,我们使用了模板标签(请参见 https://docs.djangoproject .com / en / 1.8 / howto / custom-template-tags / 。在模板标签文件中,我们具有:(请注意,您可以删除有关处理日期时间的部分):

We did something similar. In our code we used template tags (see https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/. In the template tags file we have: (Note you can remove the part about handling datetimes):

from django import template
from datetime import date, datetime, timedelta

register = template.Library()

@register.filter(expects_localtime=True)
def is_today(value):
    if isinstance(value, datetime):
        value = value.date()
    return value == date.today()

@register.filter(expects_localtime=True)
def is_past(value):
    if isinstance(value, datetime):
        value = value.date()
    return value < date.today()

然后,您可以在模板中执行以下操作:

Then in the template you can do:

 {% if this_date_object|is_today  %} <span class="active">{{field}}</span> {% endif %}
 {% if this_date_object|is_past   %} <span class="past"> {{field}}</span> {% endif %}

这里的小好处是1)您可以在其他地方重复使用日期比较,和2)您不要仅使用与显示方式相关的代码来使模型混乱。

Small advantages here are 1) you can reuse the date comparison in other places, and 2) your don't clutter your model with code only relevant to how it is to be displayed.

这篇关于比较模型中所有DateField的日期与当前日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆