</>
Skip to content
Django lessons (14/43)

Django — Model Fields

Text Fields

name = models.CharField(max_length=100)      # Short text
slug = models.SlugField(unique=True)         # URL-safe text
email = models.EmailField()                  # Email validation
url = models.URLField()                      # URL validation
text = models.TextField()                    # Long text

Number Fields

age = models.IntegerField()                  # Integer
price = models.DecimalField(                 # Decimal
    max_digits=10, decimal_places=2
)
rating = models.FloatField()                 # Float
positive = models.PositiveIntegerField()     # Positive only
small = models.SmallIntegerField()           # -32768 to 32767

Date/Time Fields

date = models.DateField()                    # Date only
time = models.TimeField()                    # Time only
datetime = models.DateTimeField()            # Date and time
auto_now = models.DateTimeField(auto_now=True)          # On save
auto_now_add = models.DateTimeField(auto_now_add=True) # On create

File Fields

document = models.FileField(upload_to='documents/')
image = models.ImageField(upload_to='images/')

Relationship Fields

# ForeignKey (Many-to-One)
author = models.ForeignKey(User, on_delete=models.CASCADE)

# ManyToManyField
tags = models.ManyToManyField(Tag)

# OneToOneField
profile = models.OneToOneField(User, on_delete=models.CASCADE)

Field Validation

from django.core.validators import MinValueValidator, MaxValueValidator

age = models.IntegerField(
    validators=[MinValueValidator(0), MaxValueValidator(120)]
)

Mini Practice

  1. Create a model with various field types
  2. Add validators to fields
  3. Set up file and image fields
  4. Create relationships

Up Next

Continue with Queries — querying the database with ORM.

Related Topics

Frequently Asked Questions about Model Fields

What is Model Fields in Django?

Model Fields is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Model Fields?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Model Fields.

Why is Model Fields important in Django?

Model Fields is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.