A model is a Python class that describes a database table. Each field represents a column.
Core Field Types
from django.db import models
class Task(models.Model):
# Text
title = models.CharField(max_length=200) # VARCHAR
description = models.TextField(blank=True) # TEXT
slug = models.SlugField(max_length=200, unique=True)
# Numbers
priority = models.IntegerField(default=0)
price = models.DecimalField(max_digits=10, decimal_places=2)
rating = models.FloatField(default=0.0)
# Boolean
is_done = models.BooleanField(default=False)
# Date and time
created_at = models.DateTimeField(auto_now_add=True) # set on creation
updated_at = models.DateTimeField(auto_now=True) # set on update
due_date = models.DateField(null=True, blank=True)
# Files
image = models.ImageField(upload_to='tasks/', blank=True)
document = models.FileField(upload_to='docs/', blank=True)
Field Options
| Option | Description |
|---|---|
null=True |
Allow NULL in the database |
blank=True |
Allow empty value in forms |
default=... |
Default value |
unique=True |
Enforce uniqueness in the table |
db_index=True |
Create a database index |
verbose_name='...' |
Human-readable field name |
choices — Restricted Value Sets
class Task(models.Model):
class Status(models.TextChoices):
TODO = 'todo', 'To Do'
IN_PROGRESS = 'in_progress', 'In Progress'
DONE = 'done', 'Done'
status = models.CharField(
max_length=20,
choices=Status.choices,
default=Status.TODO,
)
# Usage
task = Task.objects.create(title="Test", status=Task.Status.TODO)
task.get_status_display() # 'To Do'
Model Metadata
class Task(models.Model):
title = models.CharField(max_length=200)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created_at'] # default sort order
verbose_name = 'task'
verbose_name_plural = 'tasks'
db_table = 'custom_tasks' # custom table name
def __str__(self):
return self.title
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!