Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to analyze the M-to-N relationship in django models

Shulou Source: shulou.com Published: 2022-06-01 16:15:59 10月04日 Update

How to analyze the M-to-N relationship in django models? aiming at this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.

The following describes the M-to-N relationship in the three relationship models of django models:

M-to-N model

In the SQL language, the MRV N relationship is accomplished by establishing an intermediate relational table that defines foreign keys to the two primary tables. So it is possible to use two 1-type-1-type-1-type-n to define Mv1-n.

At the same time, the django model defines a more direct way to model the MRV N relationship, that is, to define fields of type models,ManyToManyField in either of the two models.

Many-to-many relationship:

1. Define the ManyToManyField field directly

Class Author (models.Model):

Name = models.CharField (max_length=100)

Class Book (models.Model):

Title = models.CharField (max_length=100)

Authors = models.ManyToManyField (Author)

Book= Book.objects.get (title= "Django")

Authors = Book.author_set.all () # get the list of authors of the book

Books= author [2] .book _ set.all () # get all the books written by the third author

2. Define through the intermediate table

Class Book (models.Model):

Title = models.CharField (max_length=100)

Authors = models.ManyToManyField (Author, through= "Authoring")

Class Authoring (models.Model):

Collaboration_type = models.CharField (max_length=100)

Book = models.ForeignKey (Book)

Author = models.ForeignKey (Author)

Chun_essay_compilations = Book.objects.filter (

Author__name__endswith='Chun'

Authoring__collaboration_type='essay'

)

Access many-to-many values (Many-to-Many Values)

Many-to-many works the same way as foreign keys, except that we are dealing with QuerySet rather than model instances. For example, here is how to view the author of a book:

> b = Book.objects.get (id=50) > b.authors.all () [,] > > b.authors.filter (first_name='Adrian') [] > b.authors.filter (first_name='Adam') []

Reverse query is also possible. To view all of an author's books, use author.book_set, like this:

> a = Author.objects.get (first_name='Adrian', last_name='Holovaty') > a.book_set.all () [

Tags: Model author analysis two fields questions books ways more help answers easy same easy content but at the same time lists books examples Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Redmi Xiaomi NVidia MySQL