0

In my Model I need to have Date field but with only year, standard DateField want from me also month and day, so I downloaded python package named partial_date_field, which adding Date type field but month and day are optional and everything was fine until I started creating view with filter, and unfortunatelly filter dont recognize PartialDateField type. So I'm wondering if it's ok to create Year field as CharField, is this a good solution? or maybe I can help my filter to recognize this custom type field "PartialDateField"?

I don't see any reason to not use CharField for my field where I write only Year for example "2016", but maybe there is reason to not do this?

Or maybe somehow I can force standard DateField to accept only year without month and day?

My Model:

from django.db import models

from partial_date import PartialDateField


class Book(models.Model):
    title = models.CharField(max_length=75, verbose_name='Book title')
    authors = models.CharField(max_length=150, verbose_name='Authors')
    published_date = PartialDateField(verbose_name='Publishing date')
    pages = models.CharField(max_length=4, verbose_name='Number of pages')
    language = models.CharField(max_length=2, verbose_name='Language')
    image = models.URLField(verbose_name='Image', default=None, blank=True)

my filter:

class BookFilter(FilterSet):

    class Meta:
        model = Book
        fields = ['title', 'authors', 'language', 'published_date']
Kuracha
  • 313
  • 6
  • 17
  • I would rather use `year = models.CharField('Publish year', max_length=4)` and custom validation for it. – Waket Zheng Jun 26 '19 at 01:46
  • So it's fully ok if Date field will be saved in database as CharField? Because I know that it's possible but also I'm aware that in programming if something is possible it doesn't mean that its good solution. :/ – Kuracha Jun 26 '19 at 01:50
  • 1
    Regarding you question for whether `CharField` or not, I would suggest go for a `PositiveSmallIntegerField` or `SmallIntegerField` depending upon your needed and add validation using `MaxValueValidator` or `MinValueValidator` – Saurabh Kumar Jun 26 '19 at 02:09

0 Answers0