Django: Combine a date and time field and filter

Furbeenator

I have a django model that has a date field and a separate time field. I am trying to use a filter to find a value on the latest record by date/time that is less than the current record's date time.

How do I use annotate/aggregate to combine the date and time fields into one and then do a filter on it?

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

This will return any notes from a previous date, but if I have a two notes on the same date, one at 3pm and one at 1pm, and I send the 3pm note to the function, I want to get the value of the 1pm note. Is there a way to annotate the two fields into one for comparison, or do I have to perform a raw SQL query? Is there a way to convert the date and time component into one, similar to how you could use Concat for strings?

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

Found an answer using models.Q here: 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()

I guess I just wasn't searching by the right criteria.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related