v.yildirim
v.yildirim

Reputation: 41

Django models.py year field

I created a database with population and years by IntegerField but is there any way to create the year field by datefield just for years neither months or days?

class Nufus_ilce(models.Model):
    city = models.CharField(max_length=15)
    year = models.IntegerField(default=0)
    population = models.IntegerField(default=0)
    def __str__(self):
        return '%s %s' % (self.city, self.year)

Upvotes: 0

Views: 2876

Answers (3)

jparty
jparty

Reputation: 78

No, because the DATE datatype used in SQL includes year, month and day. So "1999" does not fit the datatype. In other words, for SQL, it is not a date. If you need it to be a DATE datatype, then use DateField and store the data like "1999-01-01" or with the month and day of your choice. If you do not need it to be a DATE datatype, use the PositiveIntegerField, which should be just fine for most cases.

Upvotes: 0

Debendra
Debendra

Reputation: 1142

Well You can continue using IntegerField or convert it to CharField because we are going to convert that value to string for converting it to python datetime object.

from django.utils import timezone

class Nufus_ilce(models.Model):
    city = models.CharField(max_length=15)
    year = models.CharField(default='2012')
    population = models.IntegerField(default=0)
    def __str__(self):
        return '%s %s' % (self.city, self.year)
    @property
    def get_year(self):
        date = timezone.datetime.strptime('%Y', self.year)  # format it to datetime object. You need to convert `year` to str if it is `IntergerField`. ex: str(self.year).
        return date

Now you could just use instance.get_year.

Upvotes: 0

jpaul
jpaul

Reputation: 317

Usually models.IntegerField is a good choice for juste a year. However, if you want to perform some datetime operations, then declare your year as model.DateField and save year 2019 as date(2019, 1, 1).

Upvotes: 2

Related Questions