Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional year/month/day in Django model date field(s)

I want a Django model to have a date field in which the year, month, and day are all optional. An example value could be as generic as 2008 or as specific as May 10, 2008. Is it possible to define a DateField to behave this way? Or am I better off defining year/month/day as separate integers, like this?

model Book(models.Model):
    publication_year = models.IntegerField(blank=True, null=True)
    publication_month = models.IntegerField(blank=True, null=True)
    publication_day = models.IntegerField(blank=True, null=True)
like image 481
Joe Mornin Avatar asked Jul 05 '12 22:07

Joe Mornin


2 Answers

The django-date-extensions at https://github.com/dracos/django-date-extensions (by me, for exactly for this purpose) includes an ApproximateDate object to handle dates that might not have a month or a day.

like image 59
M Somerville Avatar answered Oct 17 '22 12:10

M Somerville


The Django class DateTimeField is based on the python datetime.datetime class where year, month and day are mandatory:

datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])

In your place, instead of defining three integer fields I would use the Django DateTimeField and and a boolean which tels me if I should take only the year or the whole date.

like image 36
ScotchAndSoda Avatar answered Oct 17 '22 14:10

ScotchAndSoda