How To Manage Models In Django Admin Site

1. What Is A Django Model.

A Django model is used to represent a data model. In general, one model is mapped to one database table. Django model can make data manipulation easily and flexible. You do not need to care about the database table operation. What you need to do is define and use Django models.

In Django project, you should define Django model in project’s application’s file ( in this example, the file is located at DjangoHelloWorld / user_register_login / ). The model class should extends django.db.models.Model class. And you can define multiple model class in the file. For one model class, you should specify the model field name and fieldtype. There are multiple model fieldtypes, please refer Django model official web site FieldType section.

2. Define Django Model.

pycharm django user register and login example source files

This example is based on Django User Registration And Login Use Built-in Authorization Example and Django Cookie Session Example. You can read those two articles when you need.

In this example, there are two model class defined in file.

  1. Department model: This model save employee belonged department information.
  2. Employee model: Record employee information. It has two foreign key fields, one is referred to django.contrib.auth.models.User model ( Django built-in auth user model ) to record employee username and password etc, the other is referred to Department model to save employee belonged department information.

Below is the DjangoHelloWorld / user_register_login / source code.

from django.db import models
from django.contrib.auth.models import User

# create Department model, this model will be mapped to table user_register_login_department in sqlite db.
class Department(models.Model):
    # define department name and description columns, the id column will be added automatically.
    dept_name = models.CharField(max_length=1000)
    dept_desc = models.CharField(max_length=1000)

    # this function will be invoked when this model object is foreign key of other model(for example Employee model.).
    def __str__(self):
        ret = self.dept_name + ',' + self.dept_desc
        return ret

    # this is a inner class which is used to define unique index columns. You can specify multiple columns in a list or tuple.
    class Meta:
        unique_together = ['dept_name']

# create Employee model, this model will be mapped to table user_register_login_employee in sqlite db.
class Employee(models.Model):
    # Employee has two foreign key, user(Django built-in auth_user table) and department.
    user = models.ForeignKey(User, on_delete=models.CASCADE,)
    dept = models.ForeignKey(Department, on_delete=models.CASCADE,)
    emp_mobile = models.CharField(max_length=100)
    # should add the () after IntegerField, otherwise the emp_salary column will not be created.
    emp_salary = models.IntegerField()
    # if do not specify the auto_now=True attribute with value then this field can not be created.
    emp_onboard_date = models.DateTimeField(auto_now=True)

    # this method will be called when other model reference Employee model as foreign key.
    def __str__(self):
        return self.user.username + ',' + str(self.emp_salary) + ',' + str(self.emp_mobile)

    class Meta:
        unique_together = ['emp_mobile']

3. Manage Django Models In Admin Site.

After define models in Django application’s file. You can manage them in Django project admin web site follow below steps.

  1. Open a terminal and cd into your Django project folder.
  2. Then execute below command to migrate model to local sqlite database, that means the command will create model related database table in Django project’s sqlite database.
    # first go to your Django project root folder then run below scripts.
    > python3 makemigrations user_register_login
    > python3 migrate
  3. When above script execute successfully, use a sqlite browser such as sqlite studio to browse the Django project’s sqlite db file( DjangoHelloWorld / db.sqlite3 ), then you can find two tables has been created. The table name is Django-application-name_model-name.( model mapped table name are : user_register_login_department, user_register_login_employee)two django model mapped sqlite db table
  4. Add models in django application’s file. In this example, add below code in DjangoHelloWorld / user_register_login / Please see comments for detail explain.
    from django.contrib import admin
    # the module name is app_name.models
    from user_register_login.models import Department, Employee
    # this class define which department columns will be shown in the department admin web site.
    class DepartmentAdmin(admin.ModelAdmin):
        # a list of displayed columns name.
        list_display = ['id', 'dept_name', 'dept_desc']
        # define search columns list, then a search box will be added at the top of Department list page.
        search_fields = ['dept_name', 'dept_desc']
        # define filter columns list, then a filter widget will be shown at right side of Department list page.
        list_filter = ['dept_name']
    # this class define employee columns that will be shown in the employee admin web site. Note the foreign key value will be displayed automatically.
    # the foreign key is user and dept which reference other model, so the user or department model's __str__(self) method will be called and the return value will be displayed.
    class EmployeeAdmin(admin.ModelAdmin):
        # a list of displayed columns name, the user and dept foreign key will display related model's __str__(self) method returned string value.
        list_display = ['id', 'user', 'dept', 'emp_mobile','emp_salary','emp_onboard_date']
    # Register your models to admin site, then you can add, edit, delete and search your models in Django admin site., DepartmentAdmin), EmployeeAdmin)
  5. Now login Django project admin web site use url And you can see below user_register_login app’s model list page.
    django app models table list page
  6. Click Add link at the end of each model to add Department and Employee like below.
    add department
    add employee
  7. Below is the Department list page.
    department list page with search column widget and filter widget
  8. Below is the Employee list page. Please note the DEPT filed value in the list is the string that Department model class’s __str__(self) method returned.
    django employee list page
  9. Now browse the Django project sqlite database table again, you can find the department and employee data has been added in related tables.
(Visited 37 times, 1 visits today)
READ :   How To Use Django Test Client To Test Views

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.