How to represent month as field on django model
How a specific calendar month should be represented as a field for data referring to an entire month, for example. March 2015, not on a specific day during that month. Django provides a class models.DateField
, but requires the day to be specified. I'm looking for MonthField
.
I am looking for the most pythonic and "Django" way to handle this situation. I have encountered this situation several times and would like to know what is the "correct" way to deal with it.
I know this question. The advantages and disadvantages of a string-based approach or comparison with other solutions are not discussed.
Some of the views I am considering include:
- Use a date field and set the day to the 1st of the month.
- Use a single integer to be interpreted in "months from January 1900" mode.
- Use two separate integer fields, year and month.
- Use a character field like "2015-03"
I think the solution is to use a custom field (subclass models.Field
as per https://docs.djangoproject.com/en/dev/howto/custom-model-fields/ ) using one of the above, with appropriate widgets, validation and so on, but I'll also go over the answers that suggest alternative solutions.
A similar issue is data specific to a specific week, for example. staff schedules. I've dealt with this in the past by creating a model WorkWeek
, although I suspect this is the wrong way to go because I am storing data in a database that is already available in the built-in python libraries.
source to share
I would recommend that you continue to use Django models.DateField
, as it will allow you to keep calendar queries executed across time series and this can save you a potential rebuild case.
When displaying model data, use the available options datetime
to display only the month of the year. When creating data, you can simply present users with a custom form widget and update the date to the 1st of the month when the form is validated.
source to share