Django-42-ORM many to many query (ManyToManyField created automatically)

Keywords: Django

Premise (initial table data)

The difference between manual creation and automatic creation is that there is no third operable table in the automatically created table, and there is no difference in other tables. This article only takes automatic creation as an example

book table

author table

Book & authors table (relational table)

 

Django ABCD study.app01.views.py: create a new more to more select 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_select_db(request):
    return HttpResponse("query was successful")

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

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

 

Query operation: Method 1 (forward query)

def more_to_more_select_db(request):
    # The author list stores the qualified authors
    # Find out the author of "interface test"
    author_list = []
    book_obj = Book.objects.get(name="Interface test")
    author_obj = book_obj.authors.all().values("name")
    for ath in author_obj:
        author_list.append(ath)
    return HttpResponse("Query results:%s"%author_list)

Operation status access view

 

Query operation: mode 2 (reverse query)

def more_to_more_select_db(request):
    # Book list store books that meet the conditions
    # Find out all the books whose author is "wang01"
    book_list = []
    author_obj = Author.objects.get(name="wang01")
    book_obj = author_obj.book_set.all().values("name")
    for ath in book_obj:
        book_list.append(ath)
    return HttpResponse("Query results:%s"%book_list)

Operation status access view

 

Query operation: Method 3 (double underlined sub table query)

def more_to_more_select_db(request):
    # Book list to store books that meet the conditions
    # Find out all the books whose author is "wang02" (look up the book sub table)
    book_list = []
    book_obj = Book.objects.filter(authors__name="wang02").values("name")
    for i in book_obj:
        book_list.append(i)
    return HttpResponse("Query results:%s"%book_list)

Operation status access view

Query operation: method 4 (double underlined parent table query)

def more_to_more_select_db(request):
    # Book list store books that meet the conditions
    # Find out all the books whose author is "wang02" (search the author's parent table)
    book_list = []
    book_obj = Author.objects.filter(name="wang02").values("book__name")
    for i in book_obj:
        book_list.append(i)
    return HttpResponse("Query results:%s"%book_list)

Operation status access view

Posted by Adthegreat on Mon, 25 Nov 2019 08:37:10 -0800