'Django date field derived from timestamp field
I have a created_date field:
class Comment(models.Model):
created_date = models.DateTimeField(auto_now_add=True)
I want a field derived from created_date that ideally exists in the model. I know in SQL I can do:
SELECT created_date::date
FROM Comment
How would I define that in the Django model?
Edit: created_date is just an example so I can't use date.today() from datetime module. Also note ultimate goal is to make a slug with a few different fields include the desired 'date_only' field.
Solution 1:[1]
You can use the __date lookup [Django-doc] when filtering or in F-expression, or for older versions of Django you can use the TruncDate function [Django-doc].
So you can for example filter Comments for a specific date with:
from datetime import date
Comment.objects.filter(created_date__date=date(2022, 4, 9))
Using …_date however makes not much sense: it is a datetime object, so the name of your field hints that it is a DateField, it might be better to use created, or created_timestamp.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
