How should a specific calendar month be represented as a field for data that relates to a whole month, eg. March 2015, and not to a particular day within that month. Django provides the models.DateField
class but it requires that the day be specified. What I'm looking for is a MonthField
.
I'm looking for the most pythonic and "Django" way of dealing with this situation. I've encountered this situation multiple times now and would love to know what is the "right" way to deal with it.
I am aware of this question. There is no discussion of the advantages and disadvantages of the string based approach or comparison to other solutions.
Some representations I'm considering include:
I think the solution is to use a custom field (subclass of models.Field
as per https://docs.djangoproject.com/en/dev/howto/custom-model-fields/), using one of the representations above, with associated widgets, validation etc. but I would also consider answers offering alternative solutions.
A similar problem is data that relates to a specific week eg. employee timesheets. I dealt with this in the past by creating by creating a WorkWeek
model, though I suspect this is the wrong way because I'm storing data in the database that is available already in the builtin python libraries.
I would recommend you continue using Django's models.DateField
, since this will allow your to retain calendar queries performed on time-based series and it might save you from a potential case of overengineering.
When displaying the model data, use the available datetime
functions to display just the month of the year. When authoring the data, you can simply present users with a custom form widget and update the date to the 1st of the month when the form validates.
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