Python Django's Manytomany Brief

Source: Internet
Author: User

Django's many-to-many relationship

There's a one-to-many, many-to-many relationship in the Django relationship
We're talking about a lot-to-many relationship here.

= = We'll start by designing a table structure for the example = =

# -*- coding: utf-8 -*-from __future__ import unicode_literalsfrom 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 that this many-to-many relationship is in the author's table
In fact, many pairs of relationships can exist on either side
We are now putting this relationship on the side of the author.
The author and the book are many-to-many relationships
Let's create some test data now.

In [1]: from app_many_models_01 import modelsIn [2]: models.Author.objects.create(name = u‘张三‘)Out[2]: <Author: 张三>In [3]: models.Author.objects.create(name = u‘赵一‘)Out[3]: <Author: 赵一>In [4]: models.Author.objects.create(name = u‘张六‘)Out[4]: <Author: 张六>In [5]: models.Author.objects.create(name = u‘李七‘)Out[5]: <Author: 李七>
In [6]: models.Book.objects.create(name = u‘python编程‘)Out[6]: <Book: python编程>In [7]: models.Book.objects.create(name = u‘Go编程‘)Out[7]: <Book: Go编程>In [8]: models.Book.objects.create(name = u‘Java编程‘)Out[8]: <Book: Java编程>In [9]: models.Book.objects.create(name = u‘shell编程‘)Out[9]: <Book: shell编程>In [10]: models.Book.objects.create(name = u‘Lua编程‘)Out[10]: <Book: Lua编程>In [11]: models.Book.objects.create(name = u‘Ruby编程‘)Out[11]: <Book: Ruby编程>In [12]: models.Book.objects.create(name = u‘PHP编程‘)Out[12]: <Book: PHP编程>In [13]: models.Book.objects.create(name = u‘Perl编程‘)Out[13]: <Book: Perl编程>In [14]: models.Book.objects.create(name = u‘AI编程‘)Out[14]: <Book: AI编程>

With the test data above, we created the author and book tables
Let's write the relationship of the table below

In [1]: from app_many_models_01 import modelsIn [2]: p = models.Book.objects.get(name = "Python编程")In [3]: php = models.Book.objects.get(name = "PHP编程")In [4]: pe = models.Book.objects.get(name = "Perl编程")In [5]: zhangliu = models.Author.objects.get(name = u"张六")In [6]: zhang = models.Author.objects.get(name = u"张三")In [7]: li  = models.Author.objects.get(name = u"李七")In [8]: zhao = models.Author.objects.get(name = u"赵二")

In this case, we still do not create a relationship between the tables
So, let's get started.

In [18]: zhao.m.add(p)In [65]: zhang.m.create(name=u"Basic编程")Out[65]: <Book: Basic编程>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)

Above are the actions of adding relationships from the author table
Zhang is the object of this author we've got that corresponds to Zhang San.
The relationship between the ZHANG.M and the table is the Book table object with many-to-many relationships in the author table
Zhang.m.add is to add a specific correspondence to the Book table of the author table.
And zhang.m.create This is very interesting, zhang.m is actually cross-table, across to the Book table, to the Book table, naturally can create books Ah, then this is the creation of book objects
The Add method can add one relationship at a time, or you can add multiple relationships at a time

We'll start with the Book table and add a mapping between the two tables.

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

Actually, we can see that from above.
Because many-to-many relationships are placed in the author's table, then a one-to-many relationship is
From the one side, it's all about the xxx_set mapping.
You get the result of a cross-table query of that one that corresponds to much (and here is actually many-to-many)
With this cross-table query, you can do what you want to do.

  mysql> use test_many_models; Reading table information for completion of table and column namesyou can turn off this feature to get a quicker startup W Ith-adatabase changedmysql> SELECT * from app_many_models_01_author;+----+--------+| ID |  Name |+----+--------+| 1 |  Zhang San | | 2 |  Zhao Yiqian | | 3 |  Sheet Six | | 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 | |+----+-----------+---------+10 rows in Set (0.00 sec)  

Through the query results, we can see that has been successfully added VB programming the author of this book, and from the book this table to add
We're done. To add a relationship operation, 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 |+----+| |+----+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 | |+----+-----------+---------+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 | |+----+-----------+---------+9 rows in Set (0.00 sec) 

The remove operation is to delete one or more relationships (multiple parameters can be passed in at one time)
As can be seen, after the remove operation, VB programming this book from the author of the Zhang San related books removed

Let's see the clear operation again.

mysql> select id  from app_many_models_01_author where name = "李七";+----+| 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)

Before performing the clear operation, we can see that the author Li Qi has a book numbered 16, VB programming
So, let's start with the clear operation.

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

Let's take a look at the present Li Qi what else is the author of this book?

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

Visible, clear this action clears the relationship, clears a relationship

Python manytomany summary of Django

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.