Implementation of Django Foreign Key Query
- 2021-11-10 10:22:50
- OfStack
Directory 1. 1 to many
2. Many-to-many (returned query set of objects with related classes inside)
Create 3 tables, as follows:
class Publish(models.Model):
id = models.AutoField(primary_key=True, auto_created=True)
pname = models.CharField(max_length=40)
city = models.CharField(max_length=50)
def __str__(self):
return self.pname
class Author(models.Model):
id = models.AutoField(primary_key=True, auto_created=True)
aname = models.CharField(max_length=10)
def __str__(self):
return self.aname
class Book(models.Model):
id = models.AutoField(primary_key=True, auto_created=True)
bname = models.CharField(max_length=30)
price = models.IntegerField()
publish = models.ForeignKey(Publish, on_delete=models.CASCADE)
author = models.ManyToManyField(Author)
def __str__(self):
return self.bname
1. 1 to many
Query through class attributes
# get The result of the method is 1 Objects corresponding to classes
# Inquire the name of the publishing house of a book
book = Book.objects.get(id=1)
book.publish.pname
# Inquire how many books there are under a publishing house
# Here book Yes Book The lowercase (must be lowercase) of the table name of this table plus _set
pub = Publish.objects.get(id=1)
pub.book_set.all()
Query through the double underscore (__) of Django
# Inquire about a certain company through the relevant information of the publishing house 1 Book
Book.objects.filter(publish__city=' Beijing ')
Book.objects.filter(publish__id=1)
# Query its publishing house through the relevant information of books
# Here book Yes Book The lowercase of the table name of this table (must be lowercase)
Publish.objects.filter(book__id=1)
# In values As well as values_list Use in (quotation marks must be added)
# Query its publishing house through the relevant information of books
# values The result is that 1 Query set with dictionary inside
Book.objects.filter(id=1).values('publish__pname')
# values__list The result is that 1 A query set with Yuan Zu inside
Book.objects.filter(id=1).values_list('publish__pname')
# Inquire about a certain company through the relevant information of the publishing house 1 Book
Publish.objects.filter(id=1).values('book__bname')
Publish.objects.filter(id=1).values_list('book__bname')
2. Many-to-many (returned query set of objects with related classes inside)
When many-to-many is used, Django automatically creates an additional table to store their relative relationships. The table name of the additional table here is blogs_book_author.
# Query one of the authors through their relevant information 1 Book ( The interior of the return is Book Query set of objects of)
Book.objects.filter(author__id=1)
Author.objects.filter(id=1).values('book')
# Inquire about 1 Who are the corresponding authors of this book ( The interior of the return is Author Query set of objects of)
Author.objects.filter(book__id=1)
Book.objects.filter(id=1).values('author')