A first look at Django's model

Django model

The model accurately and uniquely describes the data. It contains important fields and behaviors of the data you store. Generally speaking, each model maps a database table.

Basics:
Each model is a Python class,
and each attribute of these classes inherited from django.db.models.Model is equivalent to a database field.
Using these, Django provides an automatically generated API to access the database;

Design model

Django can be used without a database. It provides an object-relational mapper. With this technology, you can use Python code to describe the database structure.

You can use powerful data-model statements to describe your data model, which solves the problem of database schema for several years. The following is a concise example:

from django.db import models

class Reporter(models.Model):
    full_name = models.CharField(max_length=70)

    def __str__(self):
        return self.full_name

class Article(models.Model):
    pub_date = models.DateField()
    headline = models.CharField(max_length=200)
    content = models.TextField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

    def __str__(self):
        return self.headline

Correspondence between model and database

This example defines a Person model with first_name and last_name:

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

first_name and last_name are the fields of the model. Each field is designated as a class attribute, and each attribute is mapped to a database column.

The Person model above will create a database table as follows:

CREATE TABLE myapp_person (
    "id" serial NOT NULL PRIMARY KEY,
    "first_name" varchar(30) NOT NULL,
    "last_name" varchar(30) NOT NULL
);

Application data model

Next, run the Django command line utility to automatically create the database tables:

$ python manage.py makemigrations
$ python manage.py migrate

Literature reference

Address: Django 3.0API

Guess you like

Origin blog.csdn.net/p715306030/article/details/113140415