Django:结合日期和时间字段和过滤器

时间:2016-12-15 19:22:40

标签: django django-filter

我有一个django模型,它有一个日期字段和一个单独的时间字段。我试图使用过滤器按日期/时间查找最新记录的值,该值小于当前记录的日期时间。

如何使用注释/聚合将日期和时间字段合并为一个,然后对其进行过滤?

models.py
class Note(models.model):
    note_date = models.DateField(null=True)
    note_time = models.TimeField(null=True)
    note_value = models.PositiveIntegerField(null=True)

def get_last(n):
    """
        n: Note
        return: Return the note_value of the most recent Note prior to given Note.
    """
    latest = Note.objects.filter(
        note_date__lte=n.note_date
    ).order_by(
        '-note_date', '-note_time'
    ).first()

    return latest.note_value if latest else return 0

这将返回前一个日期的任何音符,但如果我在同一个日期有两个音符,一个在下午3点,一个在下午1点,我发送3pm音符到该功能,我想得到的值下午1点的说明。有没有办法将两个字段注释为一个用于比较,或者我是否必须执行原始SQL查询?有没有办法将日期和时间组件转换为一个,类似于如何将Concat用于字符串?

Note.objects.annotate(
    my_dt=Concat('note_date', 'note_time')
).filter(
    my_dt__lt=Concat(models.F('note_date'), models.F('note_time')
).first()

3 个答案:

答案 0 :(得分:1)

我来不及了,但这就是我所做的

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

notes = Note.objects.annotate(my_dt=ExpressionWrapper(F('note_date') + F('note_time'), output_field=DateTimeField()))

现在,我们添加了一个日期时间类型的新字段my_dt,并且可以进一步添加一个过滤器以进行操作

答案 1 :(得分:0)

在此处使用models.Q找到答案:filter combined date and time in django

Note.objects.filter(
    models.Q(note_date__lt=n.note_date) | models.Q(
        note_date=n.note_date,
        note_time__lt=n.note_time
    )
).first()

我想我并没有按照正确的标准进行搜索。

答案 2 :(得分:0)

这是另一种更真实的方法

from django.db.models import Value
from django.db.models.functions import Cast, Concat

notes = Note.objects.annotate(my_dt==Cast(
        Concat('note_date', Value(" "), 'note_time', output_field=DateTimeField()),
        output_field=DateTimeField()
    ).filter(my_dt_lte=datetime.now())