Creating a Django model involves defining a class that inherits from models.Model
and specifying various fields. Here’s a step-by-step guide to create a Django model with common fields:
- Install Django (if you haven’t already):
pip install django
- Start a Django Project:
django-admin startproject myproject cd myproject
- Create an App:
python manage.py startapp myapp
- Define the Model: Open the
models.py
file in your app (myapp/models.py
) and define your model. Here’s an example of aBook
model:from django.db import models class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=100) publication_date = models.DateField() isbn = models.CharField(max_length=13, unique=True) price = models.DecimalField(max_digits=6, decimal_places=2) stock = models.PositiveIntegerField() description = models.TextField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title
- Add the App to Project Settings: Add your app to the
INSTALLED_APPS
list in thesettings.py
file of your project (myproject/settings.py
):INSTALLED_APPS = [ ... 'myapp', ... ]
- Make Migrations: Create migrations for your model. Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema.
python manage.py makemigrations myapp
- Migrate the Database: Apply the migrations to your database.
python manage.py migrate
- Register the Model in the Admin Site: To make your model visible on the admin site, you need to register it. Open
admin.py
in your app (myapp/admin.py
) and register your model:from django.contrib import admin from .models import Book admin.site.register(Book)
- Run the Development Server: Start the development server to see your changes.
from django.contrib import admin from .models import Book admin.site.register(Book)
- Create a Superuser (if you haven’t already): To access the admin site, you need a superuser. Create one with the following command:
python manage.py createsuperuser
Now, you can log in to the Django admin site at http://127.0.0.1:8000/admin/
, add some Book
entries, and manage them.
References
https://docs.djangoproject.com/en/5.0/topics/db/models/
https://docs.djangoproject.com/en/5.0/ref/models/fields/