SoFunction
Updated on 2024-10-30

Django Foreign Key Query Implementation

Create three tables as detailed below:

class Publish():
    id = (primary_key=True, auto_created=True)
    pname = (max_length=40)
    city = (max_length=50)

    def __str__(self):
        return 

class Author():
    id = (primary_key=True, auto_created=True)
    aname = (max_length=10)

    def __str__(self):
        return 

class Book():
    id = (primary_key=True, auto_created=True)
    bname = (max_length=30)
    price = ()
    publish = (Publish, on_delete=)
    author = (Author)

    def __str__(self):
        return 

I. One-to-many

Querying by Class Attributes

# The result of the get method is an object of the corresponding class.
# Look up the name of the publisher of a book
book = (id=1)


# Find out how many books are under a particular publisher
# book here is the lowercase (must be lowercase) name of the table Book plus _set
pub = (id=1)
pub.book_set.all()

Queries via Django's double underscore (__)

# Search for a book by publisher's information
(publish__city='Beijing')
(publish__id=1)

# Search for the publisher through the book's information
# Here book is the lowercase (must be lowercase) name of the table Book
(book__id=1)

# Use in values and values_list (must be in quotes)
# Search for the publisher through the book's information
# values yields a query set that is internally a dictionary
(id=1).values('publish__pname')
# values__list gets a result that is a query set whose interior is a meta-ancestor
(id=1).values_list('publish__pname')

# Search for a book by publisher's information
 (id=1).values('book__bname')
 (id=1).values_list('book__bname')

II. Many-to-many (returned internally as a query set of objects of related classes)

When using many-to-many, Django automatically creates an extra table to store its relative relationships. Here the name of the extra table is blogs_book_author.

# Query one of its books by information about the author (the query set returned is internally a Book object)
(author__id=1)
(id=1).values('book')

# Query which authors correspond to a particular book (the query set returned is internally an object of Author)
(book__id=1)
(id=1).values('author')

This article on the implementation of Django foreign key query is introduced to this article , more related Django foreign key query content please search for my previous posts or continue to browse the following related articles I hope you will support me in the future more !