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()
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With