How to specify date field format while creating django objects

I have a model Team

class Team(models.Model):                             
    team = models.IntegerField(primary_key=True)      
    name = models.CharField(max_length=170)         
    code = models.CharField(max_length=20)          
    logo = models.URLField(null=True)
    country_id = models.ForeignKey('Country',null=True, on_delete=models.SET_NULL)                     
    founded = models.DateField(null=True)
    venue_name = models.CharField(max_length=170)
    venue_surface = models.CharField(max_length=170)
    venue_address = models.CharField(max_length=200)                                                
    venue_city = models.CharField(max_length=150)                                                   
    venue_capacity = models.IntegerField(null=True)                                                 
    lastModified = models.DateTimeField(auto_now=True)

I want to create object from this model where input data for founded field is only year data for example 1970

How i can do it. Thanks in advance

Upvotes: 0

Views: 210

Answers (1)

Mehak
Mehak

Reputation: 961

If you want to store just the year for the founded field, you can try PositiveSmallIntegerField for that case.

class Team(models.Model):                             
    # Other Fields                   
    founded = models.PositiveSmallIntegerField(null=True)

You can add your own validators or use clean method of your model to validate whether the user has entered the correct year or not.

If you want to use a DateField only, then you will have to give a default value to Date and Month in that case, if the year is 1970, it can be stored like 01/01/1970 and the year can be accessed using obj.founded.year

Upvotes: 1

Related Questions