Reputation: 820
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
Upvotes: 1
Views: 1273
Reputation: 542
Several solutions:
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")
__range=
:query_result= MessageLogModel.objects.filter(received_date__range=(myDate, myDate + timedelta(days=1)))
__startswith=
or __contains=
, similar usage to __date=
__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
Upvotes: 2
Reputation: 527
1.To get results in that date:
query_result= MessageLogModel.objects.filter(received_date='2021-06-11')
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'])
Upvotes: 0
Reputation: 75
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
Upvotes: 0