How to Create a Model in Django: Simple Guide
In Django, you create a model by defining a class that inherits from
django.db.models.Model. Inside this class, you add attributes using field types like CharField or IntegerField to represent database columns.Syntax
A Django model is a Python class that inherits from models.Model. Each attribute in the class represents a database field with a specific type.
- class ModelName(models.Model): defines the model.
- field_name = models.FieldType(...) defines a database column.
- Common field types include
CharFieldfor text andIntegerFieldfor numbers.
python
from django.db import models class ModelName(models.Model): field_name = models.FieldType(options)
Example
This example shows a simple Book model with a title, author, and publication year. It demonstrates how to define fields and their types.
python
from django.db import models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=50) year_published = models.IntegerField() def __str__(self): return f"{self.title} by {self.author} ({self.year_published})"
Common Pitfalls
Common mistakes when creating Django models include:
- Forgetting to inherit from
models.Model, which makes the class not a model. - Not specifying required field options like
max_lengthforCharField. - Using Python reserved words as field names.
- Not running migrations after creating or changing models.
python
from django.db import models # Wrong: missing inheritance class Car: name = models.CharField(max_length=50) # Right: class Car(models.Model): name = models.CharField(max_length=50)
Quick Reference
| Field Type | Description | Common Options |
|---|---|---|
| CharField | Text field with max length | max_length (required) |
| IntegerField | Integer number | None |
| BooleanField | True/False value | default |
| DateField | Date value | auto_now, auto_now_add |
| ForeignKey | Link to another model | to, on_delete |
Key Takeaways
Always inherit your model class from django.db.models.Model.
Define fields with appropriate field types and required options like max_length.
Run migrations after creating or updating models to apply changes to the database.
Avoid using Python reserved words as field names to prevent errors.
Use the __str__ method to make model instances readable in admin and shell.