3
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
1
I think you want to do something using the conditional update instead.
So something along the lines of:
Client.objects.update(
other_field=Case(
When(last_updated__eq=datetime.date.today(),
then=Value('OTHER_FIELD_VALUE'))
)
)
- [Django]-Django Loading Templates with Inheritance from Specific Directory
- [Django]-Django and date range picker component for Twitter Bootstrap
1
If you’re looking to filter based on date, and your model has a DateTime
field, you can simply use Django’s __date
lookup:
MyModel.objects.filter(last_updated__date=timezone.now().date()).update(...)
Also, as a general note, remember that your code’s timezone behavior will affect comparisons between timestamps and dates (i.e. the same timestamp might correspond to different dates depending on which timezone is in use).
- [Django]-Programatically populate sample data for Django Image/File fields?
- [Django]-Django queryset filter based on parent of parent
- [Django]-Stop django from automatically unicodifing POST stuff