Django-40-ORM many to many new

Keywords: Django Database

Premise (initial table data)

The book table and the author table are many to many relationships. A book may have multiple authors, and an author may have multiple books

add(* []): can be number (i.e. id); object; object list

book table

author table

Book & authors table (relational table)

Django ABCD study.app01.views.py: create a new more to more add DB view function

from django.shortcuts import render  # Import module for display page
from django.http import HttpResponse  # Module for importing display strings
from .models import *  # Model class for import operation
import datetime

# Create your views here.
def more_to_more_add_db(request):
    return HttpResponse("New success")

Django study.django study.urls: binding url and view function

url(r'^more_to_more_add_db/$', more_to_more_add_db)

 

Add operation: Method 1

def more_to_more_add_db(request):
    book_obj = Book.objects.create(name="Interface test", price=30, pub_date=pub_date=datetime.datetime.now())
    author_obj = Author.objects.get(id=1)
    book_obj.authors.add(author_obj)   # Add objects directly
    return HttpResponse("New success")

View database after startup status running

book table

book_authors table

 

New operation: mode 2

def more_to_more_add_db(request):
    book_obj = Book.objects.create(name="Interface automation test", price=40, pub_date=datetime.datetime.now())
    book_obj.authors.add(1)   # Add the id of the author table directly (wang01 author)
    return HttpResponse("New success")

View database after startup status running

book table

book_authors table

 

Add operation: Method 3 (corresponding to multiple authors)

def more_to_more_add_db(request):
    book_obj = Book.objects.create(name="performance testing", price=45, pub_date=datetime.datetime.now())
    book_obj.authors.add(1,2)   # Multiple separated by commas
    return HttpResponse("New success")

View database after startup status running

book table

book_authors table

 

Add operation: mode 4 (corresponding to all authors in the author table)

def more_to_more_add_db(request):
    book_obj = Book.objects.create(name="Jmeter Interface", price=45, pub_date=datetime.datetime.now())
    author_obj = Author.objects.all()
    book_obj.authors.add(*author_obj)   # If you are adding an iteratable object (list or tuple), add*
    return HttpResponse("New success")

View database after startup status running

book table

Table of book authors

 

Posted by samba_bal on Mon, 25 Nov 2019 09:03:07 -0800