How to compare DateTimeField with Date in Django filter funtion?

Question:

In my django app I have a MessageModel with a DateTimeField "send_date". I want to filter the messages to get all messages send a certain day (Date). How do I compare the DateTimeField with a Date to get all messages send within that day. I have try with

 query_result= MessageLogModel.objects.filter(received_date=myDate)

but it does not show the correct results. Here is the deffinition of the Model

class MessageModel(models.Model):

    sender = models.ForeignKey(User, on_delete=models.CASCADE, 
                                   related_name='+', verbose_name=_('Destinatario'), editable=False, null=True, blank=True)

    subject = models.CharField(verbose_name=_("Asunto"),max_length=50)

    send_date = models.DateTimeField(verbose_name=_("Fecha de envĂ­o") ,auto_now_add=True)
        
    message_body = models.TextField(verbose_name=_("Mensaje"))

    class Meta:
        db_table = 'riesgo_message'
        managed = True
        verbose_name = _("Mensaje")
        verbose_name_plural = _("Mensajes")

    def __str__(self):
        return self.subject
Asked By: Ernesto Ruiz

||

Answers:

If I understand you:

query_result= MessageLogModel.objects.filter(<received_date/send_date>__date=datetime.date(2021,6,5))

should help you.

please note that you dont have that field in the model.(hence the <..>)

Docs:
https://docs.djangoproject.com/en/3.2/ref/models/querysets/#date

Answered By: LiorA

Several solutions:

  1. Use date function provided by SQL(__date=):
query_result= MessageLogModel.objects.filter(received_date__date=myDate)

or:

query_result= MessageLogModel.objects.filter(received_date__date="2021-06-01")
  1. Use __range=:
query_result= MessageLogModel.objects.filter(received_date__range=(myDate, myDate + timedelta(days=1)))
  1. Use __startswith= or __contains=, similar usage to __date=
  2. Use __gt= and __lt=, similar to __range=

All of the options above are supposing you’re using the same timezone between the certain day and the data stored in database, if not, let’s say if you saved datetime field in UTC while the timezone of your variable myDate is not UTC, then you probably need to convert a pair of datetime range in UTC first, and then query database by using range or gt, lt filter

Answered By: YKL

1.To get results in that date:

query_result= MessageLogModel.objects.filter(received_date='2021-06-11')
  1. To get results in a range of dates: give start date and end date

    query_result = MessageLogModel.objects.filter(received_date__range=['2021-06-01','2021-06-11'])
    
Answered By: Sarath Chandran K
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.