Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent month as field on django model

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:

  1. Use a date field and force the day to the 1'st of the month.
  2. Use a single integer, to be interpreted in the "months since January, 1900" fashion.
  3. Use two separate integer fields, year and month.
  4. Use a character field eg "2015-03"

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.

like image 302
Matthys Avatar asked May 03 '15 17:05

Matthys


1 Answers

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.

like image 98
Filip Dupanović Avatar answered Oct 11 '22 18:10

Filip Dupanović