VIII. Multi table model operation

Environmental Science:

Create tables from relationships

First, create the django project and edit the file

from django.db import models

# Create your models here.
class Publish(models.Model):
    #If you don't write the id, it will be generated automatically. The name is nid, and it will increase automatically
    #Different databases may generate different id names automatically.
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=32)
    addr = models.CharField(max_length=64)
    email = models.EmailField()

class Author_details(models.Model):
    phone = models.CharField(max_length=16)
    sex = models.IntegerField

class Author(models.Model):
    name = models.CharField(max_length=32)
    addr = models.CharField(max_length=64)
    #OneToOneField and ForeignKey are used. The fields in the model table will be automatically added with id
    #One to one relationship: one to one field
    authordetail_id = models.OneToOneField(to='Author_details', to_field='id')

class Book(models.Model):
    #Floating point, 5 digits in total, 2 decimal places
    #To = association table to field = field in association table, one to many relationship uses ForeignKey
    #ManyToManyField will automatically create the third table many to many relationship

Migrating databases



Create Py file in the project and run the code in django environment

import os
if __name__ == '__main__':
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pro77_13.settings")
    import django

    from app01.models import *

I. multi table model creation, one to many addition and deletion, and many to many addition and deletion

Add several pieces of data to the app01 publish table

One to many new data (continued above)

#Add a book published by Beijing Publishing House
#The first way
#ret=Book.objects.create(name = 'dream of Red Mansions', price = 53.4, publish [id = 1)
# print(

#The second way is to save the object Publish = publishing object, which is an id in the database
#pk: primary key. It is found by primary key
ret=Book.objects.create(name='The Dream of Red Mansion',price=53.4,publish=publish)

App01 "book table

#One to many modification data

Method 1:

#Explanation: book.publish = publishing object

App01 "book table:

Mode two:

#Explanation: book=Book.objects.filter(pk=1).update(publish = publishing object)

App01 "book table:

Many to many new data

First of all, you need to add data to the app01'author and app01'author'details tables

App01 "author" details table:

App01 "author table:

#Add a new author named lqz,egon to the book "dream of Red Mansions"

Method 1:

book=Book.objects.filter(name='The Dream of Red Mansion').first()
# #Add add multiple objects

Tags: Python Django Database

Posted on Sat, 30 Nov 2019 15:58:10 -0800 by dabas