Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting date from Django datetime field with F() expression

Lets say I have a Django model object that requires to update a particular field if the last_updated datetime field is equal to today's date.

If I were to use F expression to avoid race condition, what would be the best way to compare the date from last_updated with current date using timezone.now().date()?

like image 369
Clueless_Coder Avatar asked Oct 20 '25 04:10

Clueless_Coder


1 Answers

If I'm not wrong, F() can't do that operation. So I would suggest another way to achieve the same by using Extract()

from django.db.models.functions import ExtractDay, ExtractMonth, ExtractYear

queryset = SampleModel.objects.annotate(day=ExtractDay('last_updated'),
                                        month=ExtractMonth('last_updated'),
                                        year=ExtractYear('last_updated')
                                        ).filter(day=timezone.now().day,
                                                 month=timezone.now().month,
                                                 year=timezone.now().year
                                                 )


This will return a QuerySet(), So you can fetch a specific instance by .get() method as below,

specific_model_instance = queryset.get(id=specific_id)


Note: I know this is litle bit long procedure. But it'll work

like image 131
JPG Avatar answered Oct 21 '25 16:10

JPG