Database (three) - many-to-many, one

We have four tables:
person_publisher

 

 person_book

 

 person_author

 

 person_author_book

 

Next, respectively, from forward query (sub-tables -> main table) and the reverse lookup (the primary table -> sub-table) for.

1. One to One

Forward queries: Queries book in id = 2 (python) corresponding Press

    book_obj=models.Book.objects.get(id=2)
    print(book_obj)
    print(book_obj.publisher.name)

Reverse lookup: Query publisher in id = (Tsinghua University Press) corresponding book 1

    publisher_obj=models.Publisher.objects.get(id=1)
    print(publisher_obj)
  #类名_set.all()
print(publisher_obj.book_set.all())

 

 2. many

Forward queries: Queries book in id = 3 (java) corresponding Press

    book_obj=models.Book.objects.get(id=3)
    print(book_obj)
    print(book_obj.publisher.name)

Reverse lookup: Query publisher of id = 3 (Guangzhou University Press) corresponding book

    publisher_obj=models.Publisher.objects.get(id=3)
    print(publisher_obj)
    print(publisher_obj.book_set.all())

 

So, if we want to query python that was published by several publishers (although generally only one), we can do this:

    book_obj=models.Book.objects.filter(title='python')
    print(book_obj)
    for i in book_obj:
        print(i.publisher)

In fact, we found that one-to-many query and basically the same.

3. to-many

Forward Search: Find all book author named gong

    author_obj=models.Author.objects.get(name='gong')
    print(author_obj.book.all())

 

 Reverse lookup: Query the book as "network-based" all authors

    = models.Book.objects.get book_obj (title = ' network based ' )
     Print (book_obj.author_set.all ())

 

 All in all, a positive inquiry direct order of acquisition, reverse lookup by class name (all lowercase) _set.all ()  to get.

Get a day, and finally a preliminary understanding of the Zenong. ! !

Guess you like

Origin www.cnblogs.com/xiximayou/p/11779899.html