0
0
Djangoframework~5 mins

Field types (CharField, IntegerField, DateField) in Django

Choose your learning style9 modes available
Introduction
Field types define what kind of data each part of your database will hold, like words, numbers, or dates.
When you want to store names or short text, use CharField.
When you need to save whole numbers like age or quantity, use IntegerField.
When you want to keep track of dates like birthdays or event days, use DateField.
Syntax
Django
class ModelName(models.Model):
    field_name = models.CharField(max_length=100)
    field_number = models.IntegerField()
    field_date = models.DateField()
CharField requires a max_length to limit how many characters it can store.
DateField stores dates without time, useful for birthdays or deadlines.
Examples
Stores a short text up to 50 characters, like a person's name.
Django
name = models.CharField(max_length=50)
Stores a whole number, such as someone's age.
Django
age = models.IntegerField()
Stores a date, for example, a birthday.
Django
birth_date = models.DateField()
Sample Program
This model defines a Person with a name, age, and birth date. Each field uses the right type to store the correct kind of data.
Django
from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    birth_date = models.DateField()

    def __str__(self):
        return f"{self.name}, Age: {self.age}, Born on: {self.birth_date}"
OutputSuccess
Important Notes
Always set max_length for CharField to avoid errors.
IntegerField only stores whole numbers, no decimals.
DateField expects a date format like YYYY-MM-DD.
Summary
CharField stores text with a max length limit.
IntegerField stores whole numbers.
DateField stores dates without time.