Django Models
Understanding Models and ORM
In Django, models are Python classes that represent database tables. Each attribute of the model class corresponds to a database field. Django uses an Object-Relational Mapping (ORM) to map these model classes to database tables, enabling us to interact with the database using Python code instead of SQL queries.
Creating Models
To create a model in Django, you need to define a class in the models.py file of your application. For our voting application, we will have two models, namely; Question and Answer models:
# models.py
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question_text
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
def __str__(self):
return self.choice_text
Here, we have imported Django's models module, which provides the base classes and functions for defining models. For instance, we have defined models named Question and Answer that inherit from models.Model, the base class for all models in Django. Inside the class, we define fields required within the model. Both models include a ‘str’ method to provide a human-readable representation of their instances.
Making and Running Migrations
After defining your models, you need to create and apply migrations to reflect the changes in your database schema.
- Create Migrations: This command generates migration files based on the changes detected in your models.
python manage.py makemigrations
- Apply Migrations: This command applies the migrations to the database, creating the corresponding tables and fields.
python manage.py migrate
Django Admin Interface
One of the key strengths of Django is its automatic admin interface. This interface utilizes metadata from your models to create a quick, model-centric platform for trusted users to manage site content. The recommended use of the admin interface is as an internal management tool for an organization. It is not designed to serve as the primary front end for your website.
Creating Admin User
To access the admin interface, you need to create a superuser. Run the following command in your terminal:
python manage.py createsuperuser
You will be prompted to enter a username, email, and password for the superuser.
HINT:
Enter your username: admin Enter your email address: [email protected] Enter your password: ********** Enter your password (again): ********** Superuser created successfully.
Starting Development Server
The admin site is activated and we can see it by running our development server.
python manage.py runserver
Then, open your browser and navigate to your localhost and go to /admin
. You will see the login page. To log in, enter the credentials you created for the superuser.
Admin Site Overview
Once logged in, you will see a list of registered models. You can add, edit, and delete entries for these models.
- Add a new object:
- Click on the model name (e.g., Question).
- Click the "Add (Question)" button.
- Fill out the form and click "Save."
- Edit an existing object:
- Click on the model name.
- Click on the object you want to edit.
- Update the form fields and click "Save."
- Delete an object:
- Click on the model name.
- Select the objects you want to delete by checking the boxes next to them.
- Choose "Delete selected questions" from the action dropdown and click "Go."
Viewing Our App in the Admin Index Page
We need to convey to the admin that Question and Answer objects have an admin interface. For this, open your admin.py
file and ensure it is like:
from django.contrib import admin
from .models import Question, Answer
admin.site.register(Question)
admin.site.register(Answer)
We can see an Add button on the left end of our models, let’s try adding some. Click on the “Add” button next to the Questions model as:
Click on the “Save” button to add the question.
Customizing the Admin Interface
You can customize how your models are displayed in the admin interface by creating a model admin class.
from django.contrib import admin
from .models import Question, Answer
class QuestionAdmin(admin.ModelAdmin):
list_display = ('question_text', 'pub_date')
search_fields = ['question_text']
class AnswerAdmin(admin.ModelAdmin):
list_display = ('choice_text', 'question', 'votes')
search_fields = ['choice_text']
admin.site.register(Question, QuestionAdmin)
admin.site.register(Answer, AnswerAdmin)