This is the 8th day of my participation in Gwen Challenge

What is Django’s Model?

You can add, delete, change, or query a database using SQL statements. Django uses Object Mapping (ORM) technology to encapsulate database operations into operations on classes and objects, in this case models. Each model maps a database table that accurately and uniquely describes the data. Important fields and behaviors that contain stored data.

  • Each Model is a Python class that extends from Django.db.models.Model
  • Each attribute of a model class is equivalent to a database field
  • Django provides an API that automatically generates access to databases, such as additions, changes, and so on

Why not just use SQL statements?

With ORM framework, developers no longer have to consider the optimization of native SQL, nor the problem of database migration. ORM has been optimized and supports a variety of databases, which can greatly improve the development efficiency.

Get a quick look at the process of using A Django Model

  1. Define the model

Define the model fields (class attributes) in models.py

from django.db import models

class Person(models.Model) :
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    
SQL statements generated by the corresponding database table of this model are as follows:
# CREATE TABLE myapp_person ("id" serial NOT NULL PRIMARY KEY,"first_name" varchar(30) NOT NULL,"last_name" varchar(30) NOT NULL);
Myapp_person = myapp_person = myapp_person
The # id field is automatically added as the primary key, and can be overwritten
The syntax for creating a table is PostgreSQL. Django generates SQL statements based on the database backend specified in the configuration file.
Copy the code
  1. Database migration (creation)
    1. Register application: in the Settings filesetting.pyIn theINSTALLED_APPSAdd the name of the application in which the model resides
INSTALLED_APPS = [
    #...
    'myapp'.#...
]
Copy the code
2. Database migration: After configuring the post-model, you need to manually migrate the database to create the corresponding databaseCopy the code
manage.py makemigrations
manage.py migrate
Copy the code
  1. Using the model

Djangos models are actually classes, so they are used the same way as normal classes and objects

# create object
p = Person(name="Fred Flintstone", shirt_size="L")

Save the object's data to the database
p.save()

Read information about the object
p.shirt_size
# 'L'
Use object methods
p.get_shirt_size_display()
# 'Large'
Copy the code