Django model class operation data table

1. Create a project

django-admin startproject my_first_django   # 创建一个名称为my_first_django的项目

After the command is executed, a folder with the project name and a manage.py file will be generated

manage.py is the management file of the project.

The structure in my_first_django is as follows:

                     

 

A functional module in Django development is implemented by an application

2. Create an application

python manage.py startapp booktest        # 创建一个booktest的应用

                

After the application is created, it needs to be registered

Modify the INSTALLED_APPS configuration item in the setting.py file in my_first_django.

Run django web service

python manage.py runserver

Introduction to ORM (Object-Relations-Mapping), Django has built-in ORM framework by default

3. Create a book model

from django.db import models


# Create your models here.

# 设计和表对应的类 : 模型类

# 图书类
class BookInfo(models.Model):
    """
    图书模型类
    """
    bname = models.CharField(max_length=20)
    bpub_data = models.DateField()

Django will create the corresponding table in the database according to the model class

The model class generation table is divided into two steps:

        1) Generate migration file

python manage.py makemigrations

        2) Perform migration to generate a table

python manage.py migrate

                            

The format of the table name created in the database is: application name_model class lowercase

The indication in this example is "booktest_bookinfo"

4. Operate the data table through the model class (addition, deletion, modification, and check)

1) Increase records

from booktest.models import BookInfo
from datetime import date


# 数据库中增加记录
# 1 实例化模型类
# 2 添加实例属性    实例属性的名称需要了模型类中的类属性名称一致
# 3 实例调用save()方法完成记录的插入
b = BookInfo()
b.bname = "天龙八部"
b.bpub_data = data(1990,1,1)
b.save()

2) Query records

from booktest.models import BookInfo


# 查询记录的步骤:
# 1 调用模型类的objects.get()方法 参数为查询条件
# 2 接收1中的返回的结果,类型了模型类的一个实例
# 3 查看 2 中实例的属性即可

b2 = BookInfo.objects.get(bname="天龙八部")
print(b2.bname)
print(b2.bpub_data)

(3) Modification record

from booktest.models import BookInfo


# 修改记录的步骤:
# 1 先查询到要修改的记录,得到其实例
# 2 对其实例属性进行修改
# 3 调用save()方法

b3 = BookInfo.objects.get(bname="天龙八部")
b3.bname = "天龙八部2"
b3.save()

4) Delete record

from booktest.models import BookInfo


# 修改记录的步骤:
# 1 先查询到要修改的记录,得到其实例
# 2 调用该实例的delete()方法

b4 = BookInfo.objects.get(bname="天龙八部2")
b4.delete()

5. Add one-to-many relationship

Description: Add a hero class. The hero has the name, gender, ultimatum, and the book attribute of the origin. The book origin is the foreign key of the book table. The book list and the hero list have a one-to-many relationship.

1) Create a hero model class

from django.db import models


# Create your models here.

# 设计和表对应的类 : 模型类

# 图书类
class BookInfo(models.Model):
    """
    图书模型类
    """
    bname = models.CharField(max_length=20)
    bpub_data = models.DateField()


# 英雄类
class HeroInfo(models.Model):
    """
    英雄模型类
    """
    h_name = models.CharField(max_length=20)
    h_gender = models.BooleanField(default=False)
    h_comment = models.CharField(max_length=128)
    h_book = models.ForeignKey("BookInfo", on_delete=models.CASCADE)

Among them, models.ForeignKey("BookInfo", on_delete=models.CASCADE), the first parameter is the class name of "one" in "one" to "many", and the second parameter is when deleting "one" "Multiple" approach. models.CASCADE indicates that when deleting "one", the corresponding deletion of "multiple" is taken (cascade deletion).

The possible values ​​of on_delete are as follows:

  • CASCADE: This is the default option, cascade delete, you don't need to specify it explicitly.
  • PROTECT: Protected mode. If this option is used, an ProtectedErrorerror will be thrown when deleting .
  • SET_NULL: Blank mode, when deleting, the foreign key field is set to be empty, provided that blank=True, null=Truewhen the field is defined , it is allowed to be empty.
  • SET_DEFAULT: Set the default value. When deleting, the foreign key field is set to the default value, so pay attention to adding a default value when defining the foreign key.
  • SET(): Customize a value, which of course can only be the corresponding entity

2) Update and execute the migration file (refer to 3.1 and 3.2)

3) Add hero record

import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_first_django.settings")  # my_first_django 项目名称
django.setup()


from booktest.models import BookInfo, HeroInfo
from datetime import date

b1 = BookInfo()
b1.bname = "天龙八部"
b1.bpub_data = date(1989, 10, 5)
b1.save()

b2 = BookInfo()
b2.bname = "神雕侠侣"
b2.bpub_data = date(1999, 1, 20)
b2.save()

h1 = HeroInfo()
h1.h_name = "乔峰"
h1.h_gender = False
h1.h_comment = "降龙十八掌"
# 注意 在添加英雄的h_book属性时类型为 BookInfo的实例
h1.h_book = b1
h1.save()

h2 = HeroInfo()
h2.h_name = "段誉"
h2.h_gender = False
h2.h_comment = "六脉神剑"
h2.h_book = b1
h2.save()

h3 = HeroInfo()
h3.h_name = "杨过"
h3.h_gender = False
h3.h_comment = "独臂神功"
h3.h_book = b2
h3.save()

h3 = HeroInfo()
h3.h_name = "小龙女"
h3.h_gender = True
h3.h_comment = "睡树枝"
h3.h_book = b2
h3.save()

       

There is an h_book_id field in the booktest_heroinfo table, which corresponds to h_book in the class attribute

4) View the book attributes of the hero

hero = HeroInfo.objects.get(h_name="小龙女")
print(hero.h_name)
print(hero.h_gender)
print(hero.h_book)
print(hero.h_book.bname)
print(hero.h_book_id)

5) View all heroes corresponding to a certain title

# 查询书籍的对象

b1 = BookInfo.objects.get(bname="天龙八部")
print(b1.bname)

# 查询书籍对应的所有英雄   使用 b1.heroinfo_set.all() 返回的是一个列表,里面存放的是每个英雄的实例

for hero in b1.heroinfo_set.all():
    print(hero.h_name)
    print(hero.h_comment)
    print()

6) All content in the query table

# 返回一个列表,列表里面是每本书的实例
BookInfo.objects.all()

Guess you like

Origin blog.csdn.net/qq_39197555/article/details/113809570