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.
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.
After defining your models, you need to create and apply migrations to reflect the changes in your database schema.
python manage.py makemigrations
python manage.py migrate
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.
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: admin@admin.com Enter your password: ********** Enter your password (again): ********** Superuser created successfully.
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.
Once logged in, you will see a list of registered models. You can add, edit, and delete entries for these models.
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.
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)