I want to compare a DateField and a TimeField in a queryset with the current date. I searched for hours but did not find anything. Tried much with Q/F-Object but no solution, too. And now I am here and hope someone knows how to solve this :) - Btw. splitting into date and time is not my fault and there is no way to change it into a DateTimeField (too much dependencies in other projects).

class Model(models.Model):
    date = models.DateField()
    time = models.TimeField()

In MySQL I would do something like:
SELECT * FROM app_model WHERE CAST(CONCAT(CAST(date as CHAR),' ',CAST(time as CHAR)) as DATETIME) >= NOW()

Thanks for any suggestions!

有帮助吗?

解决方案

You can do this with or'd queryset contraints (Q objects):

now = datetime.datetime.now()
future_models = Model.objects.filter(Q(date__gt=now.date()) | (Q(date=now.date()) & Q(time__gte=now.time())))

That selects all instances for which date is past today, and all instances for which date is today and the the time is greater than or equal to the current time.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top