Django The many to many relationship of

stay Django In a relationship , There's one on one , One to many , many-to-many

We're talking about the many to many relationship here

Let's first design a table structure for the example

# -*- coding: utf-8 -*-
from __future__ import unicode_literals from django.db import models # Create your models here. class Book(models.Model):
name = models.CharField(max_length = 32) def __str__(self):
return self.name.decode("utf-8") def __unicode(self):
return self.name.decode("utf-8") class Author(models.Model):
name = models.CharField(max_length = 32)
m = models.ManyToManyField('Book') def __str__(self):
return self.name.decode("utf-8") def __unicode(self):
return self.name.decode("utf-8")

We can see , This many to many relationship is In the author's table

in fact , Many to many relationships can exist on either side

We now put the relationship on the author's side

Authors and books are many to many

Now let's create some test data

In [1]: from app_many_models_01 import models
In [2]: models.Author.objects.create(name = u' Zhang San ')
Out[2]: <Author: Zhang San > In [3]: models.Author.objects.create(name = u' Zhao Yi ')
Out[3]: <Author: Zhao Yi > In [4]: models.Author.objects.create(name = u' Zhang Liu ')
Out[4]: <Author: Zhang Liu > In [5]: models.Author.objects.create(name = u' Li Qi ')
Out[5]: <Author: Li Qi >
In [6]: models.Book.objects.create(name = u'python Programming ')
Out[6]: <Book: python Programming > In [7]: models.Book.objects.create(name = u'Go Programming ')
Out[7]: <Book: Go Programming > In [8]: models.Book.objects.create(name = u'Java Programming ')
Out[8]: <Book: Java Programming > In [9]: models.Book.objects.create(name = u'shell Programming ')
Out[9]: <Book: shell Programming > In [10]: models.Book.objects.create(name = u'Lua Programming ')
Out[10]: <Book: Lua Programming > In [11]: models.Book.objects.create(name = u'Ruby Programming ')
Out[11]: <Book: Ruby Programming > In [12]: models.Book.objects.create(name = u'PHP Programming ')
Out[12]: <Book: PHP Programming > In [13]: models.Book.objects.create(name = u'Perl Programming ')
Out[13]: <Book: Perl Programming > In [14]: models.Book.objects.create(name = u'AI Programming ')
Out[14]: <Book: AI Programming >

Through the above test data , We created author tables and Book tables

Next, we will write the relationship of the table

In [1]: from app_many_models_01 import models
In [2]: p = models.Book.objects.get(name = "Python Programming ")
In [3]: php = models.Book.objects.get(name = "PHP Programming ")
In [4]: pe = models.Book.objects.get(name = "Perl Programming ")
In [5]: zhangliu = models.Author.objects.get(name = u" Zhang Liu ")
In [6]: zhang = models.Author.objects.get(name = u" Zhang San ")
In [7]: li = models.Author.objects.get(name = u" Li Qi ")
In [8]: zhao = models.Author.objects.get(name = u" Zhao er ")

Here we are , We still haven't created relationships between tables

that , Let's get started

In [18]: zhao.m.add(p)
In [65]: zhang.m.create(name=u"Basic Programming ")
Out[65]: <Book: Basic Programming > In [66]: zhang.m.add(php) In [67]: zhang.m.add(pe) In [68]: zhang.m.add(p,php,pe) In [69]: zhang.m.add(p,php,pe,go)

The above are all operations of adding relationships from the author table

zhang It's what we got, corresponding to Zhang San's The author's object

zhang.m The relationship between the corresponding tables is the book table object of many to many relationship in the author table

zhang.m.add It is to add a specific corresponding point to the corresponding relationship of the book table of the author table

and zhang.m.create This is very interesting ,zhang.m In fact, it's cross table , Across to the book list , To the book list , Naturally, books can be created , So that's creating a Book object

add Method can add one relationship at a time , You can also add multiple relationships at once


Let's start from the list of books , To add a mapping between two tables

In [73]: zhang.m.create(name=u"vb Programming ")
Out[73]: <Book: vb Programming > In [74]: b = models.Book.objects.get(name = u"vb Programming " ) In [75]: b.author_set.all()
Out[75]: <QuerySet [<Author: Zhang San >]>

In fact, we can see from the above

Because the many to many relationship is in the author table , So what's similar to a one to many relationship is

From the side of one , They all use XXX_set This kind of mapping

I got this one corresponding to many ( And here is actually many to many ) The result of the cross table query of the party with more than

Through this cross table query operation , You can do what you want to do

mysql> use test_many_models;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A Database changed
mysql> select * from app_many_models_01_author;
+----+--------+
| id | name |
+----+--------+
| 1 | Zhang San |
| 2 | Zhao Yi |
| 3 | Zhang Liu |
| 4 | Li Qi |
+----+--------+
4 rows in set (0.00 sec)
mysql> select * from app_many_models_01_author_m;
+----+-----------+---------+
| id | author_id | book_id |
+----+-----------+---------+
| 11 | 1 | 1 |
| 16 | 1 | 2 |
| 14 | 1 | 7 |
| 15 | 1 | 8 |
| 12 | 1 | 14 |
| 13 | 1 | 15 |
| 17 | 1 | 16 |
| 7 | 3 | 3 |
| 6 | 3 | 9 |
| 18 | 4 | 16 |
+----+-----------+---------+
10 rows in set (0.00 sec)

Through the query results , We can see , Has successfully added vb Programming is the author of this book , And it was added from the book table

That's it. Add relationship , Let's talk about deleting and clearing relationships

In [77]: zhang.m.remove(b)


mysql> select id from app_many_models_01_book where name="vb Programming ";
+----+
| id |
+----+
| 16 |
+----+
1 row in set (0.00 sec) mysql> select * from app_many_models_01_author_m;
+----+-----------+---------+
| id | author_id | book_id |
+----+-----------+---------+
| 11 | 1 | 1 |
| 16 | 1 | 2 |
| 14 | 1 | 7 |
| 15 | 1 | 8 |
| 12 | 1 | 14 |
| 13 | 1 | 15 |
| 17 | 1 | 16 |
| 7 | 3 | 3 |
| 6 | 3 | 9 |
| 18 | 4 | 16 |
+----+-----------+---------+
10 rows in set (0.00 sec) mysql> select * from app_many_models_01_author_m;
+----+-----------+---------+
| id | author_id | book_id |
+----+-----------+---------+
| 11 | 1 | 1 |
| 16 | 1 | 2 |
| 14 | 1 | 7 |
| 15 | 1 | 8 |
| 12 | 1 | 14 |
| 13 | 1 | 15 |
| 7 | 3 | 3 |
| 6 | 3 | 9 |
| 18 | 4 | 16 |
+----+-----------+---------+
9 rows in set (0.00 sec)

remove The operation is to delete one or more relationships ( You can pass in more than one parameter at a time )

You can see , After remove operation , Just put vb The book of programming has been removed from Zhang San's related books


Let's see clear operation

mysql> select id from app_many_models_01_author where name = " Li Qi ";
+----+
| id |
+----+
| 4 |
+----+
1 row in set (0.00 sec) mysql> select book_id from app_many_models_01_author_m where author_id="4";
+---------+
| book_id |
+---------+
| 16 |
+---------+
1 row in set (0.00 sec)

In execution clear Before operation , We can see that the author Li Qi has a Book , The number is 16, namely vb Programming

that , We started to execute clear operation

In [78]: li.m.clear()

Let's see what other books Li Qi has now ?

mysql> select book_id from app_many_models_01_author_m where author_id="4";
Empty set (0.00 sec)

so ,clear This kind of operation is to clear the relationship , Remove all of a relationship

python django Of ManyToMany More related articles in brief

  1. Django Of Many-to-Many( Many to many ) Model

      Django Of Many-to-Many( Many to many ) Model date :2012-05-05 |  source : Unknown  |  author :redice |  People gathered around  |  1 People applauded ! Kun Peng Web Data capture - major Web ...

  2. be based on Python+Django Of Kubernetes Cluster management platform

    * More technical dry goods please stamp : Listen to the cloud blog today , Contact kubernetes It's been a while , And most of our businesses have been running stably in different scales kubernetes On the cluster , Have to say , Whether it's from application deployment . iteration , Or from resources ...

  3. python——django Use mysql database ( Two )

    In the previous , We've talked about how to initialize a django database , This chapter will talk about how to use our initialized database in the actual project ? If the database operation has not been initialized , Please refer to python——django Use mysql database ...

  4. python——django Use mysql database ( One )

    I've written about how to create a django project , Now we have a little skeleton , To think about this web Engineering becomes a flesh and blood person , We need to do a lot more . Now let's first introduce how to django Use in mysql database . Premise : already ...

  5. How to view PYTHON Django The path to save

    How to view PYTHON Django The path to save $ python -c " import sys sys.path = sys.path[1:] import django print(dja ...

  6. python Django course And Model ( database )、 Customize Field、 Data sheet changes 、QuerySet API

    python  Django course   And Model ( database ). Customize Field. Data sheet changes .QuerySet API One .Django  Model ( database ) Django The model is database related , Database related code ...

  7. python Django course Template rendering 、 loop 、 conditional 、 Common labels 、 filter

    python3.5 manage.py runserver python Django course Template rendering . loop . conditional . Common labels . filter One .Django Templates render templates 1. Create a zqxt_tm ...

  8. python Django course And install 、 Basic commands 、 Views and websites

    python  Django course   And install . Basic commands . Views and websites One . brief introduction Django It provides modules that are often used to develop websites , Common code has been written for you , By reducing duplicate code ,Django Enables you to focus on w ...

  9. python django Multi level business tree structure planning and page rendering

    summary : In the project , Parent to child structures are not uncommon , If it's just a two-tier tree structure , We can use the foreign key design of the database to do it easily , The child business table designs a field foreign key to the parent business table , So the son comes to the father . Parent to child queries are very simple . But often the father son structure has ...

Random recommendation

  1. PAT 1033. Old keyboard typing (20)

    Some keys on the old keyboard are broken , So when you type a paragraph , The corresponding character will not appear . Now give a paragraph of text that should be entered . And the broken keys , What will the text look like ? Input format : Enter in 2 The broken keys are given separately in the line . And the text that should be entered ...

  2. Simple and convenient div Vertical center .

    What's discussed here is , There is only one... In a parent container DIV, This DIV The problem of vertical centering relative to the parent element : Here are three ways : Here for clarity , It's all used sass How to write it . One : Applicable to sub elements with specific width and height .wrap{ // Parent element ...

  3. 【bzoj3991】 Treasure hunt game

    http://www.lydsy.com/JudgeOnline/problem.php?id=3991 ( Topic link ) The question Give a n A weighted tree of nodes ,m Each operation modifies one key point at a time , After each operation , From which ...

  4. PHP5 Use in PDO How to connect to the database

    PDO(PHP Data Object) yes PHP What's in it , yes PHP 5 A major new feature , Because in PHP 5 Former php4/php3 They are all a bunch of database extensions to connect and process with various databases ,php_my ...

  5. [Android Studio] Button learning

    Android Studio Button 1. Add a button Create a new one Blank Project after , stay activity_main.xml: Add a button to , have access to design Pattern to add ,: ...

  6. 【linux Commands and tools 】ethtool command

    ethtool Is used to query and set network card parameters command . If command not found It can be used apt-get/yum add to . main parameter : ethtool ethX// see ethX Device properties ethtool ...

  7. 【PYTHON】 The user logs in three times and is locked incorrectly

    The blacklist :blacklist.txt User list :username_password.py # Author:Stephen Yuan # User name and password username_password = { ', ...

  8. sqlserver Isolation level - turn

    SQL-92 Four isolation levels are defined in the standard , These four isolation levels are in the previous version of SQL Server We are supported in the middle of the war : READ UNCOMMITTED READ UNCOMMITTED It's the least restrictive level of isolation , Because of this level ...

  9. tp frame php ajax land

    html file <form class="form-signin loginform" role="form"> <input type=&q ...

  10. Qt Next libusb-win32 Use ( Two ) Batch read and write operations

    One . summary Study libusb-win32 Use . Use batch transmission mode and USB Development board for data reading . Write operations . The upper computer uses Qt Do the interface ,  Use USB The endpoint of the development board 2 As a batch transport endpoint . Two . Realization Simple code , Give directly , Such as ...