django manytomany

转载:http://my.oschina.net/u/572994/blog/105280

例如有如下模型

models.py

1
2
3
4
5
6
7
from django.db import models
 
class person(models.Model):
    name = CharField(max_length=30)
 
class book(models.Model):
    auther = ManyToManyField(person)<span></span>

假设p为一个person对象,b为一个book对象

1
2
3
4
5
6
7
8
9
10
11
#添加关联
b.auther.add(p)
 
#去除关联
b.auther.remove(p)
 
#返回所有作者
b.auther.all()
 
#反向查询,返回这个人写的所有书,book即为反向查询的模型名
p.book_set.all()

如果在models.py中

1
2
3
4
5
6
7
8
9
from django.db import models
 
class person(models.Model):
    name = CharField(max_length=30)
 
class book(models.Model):
    #当关联同一个模型的字段大于一个时,要使用related_name参数来指定表名
    auther = ManyToManyField(person,related_name="auther")
    translater = ManyToManyField(person,related_name="translater")

此时反向查询p.book_set.all()不可用,取而代之的为

1
2
3
4
5
#返回该人写的所有书,book_set被related_name中指定的表名代替
p.auther.all()
 
#返回该人翻译的所有书
p.translater.all()

转载:http://blog.csdn.net/fengyu09/article/details/17434795

要定义多对多关系,使用ManyToManyField字。 (注:django版本1.4)

    本例中,一篇文章可以被很多出版社发表,而一个出版社也会发表多个文章。

  1. from django.db import models  
  2.   
  3. class Publication(models.Model):  
  4.     title = models.CharField(max_length=30)  
  5.   
  6.     # On Python 3: def __str__(self):  
  7.     def __unicode__(self):  
  8.         return self.title  
  9.   
  10.     class Meta:  
  11.         ordering = ('title',)  
  12.   
  13. class Article(models.Model):  
  14.     headline = models.CharField(max_length=100)  
  15.     publications = models.ManyToManyField(Publication)  
  16.   
  17.     # On Python 3: def __str__(self):  
  18.     def __unicode__(self):  
  19.         return self.headline  
  20.   
  21.     class Meta:  
  22.         ordering = ('headline',)  

接下来我们使用Python API 功能执行操作的例子。

创建两个出版社:

  1. >>> p1 = Publication(title='The Python Journal')  
  2. >>> p1.save()  
  3. >>> p2 = Publication(title='Science News')  
  4. >>> p2.save()  
  5. >>> p3 = Publication(title='Science Weekly')  
  6. >>> p3.save()  

新建一个文章:

  1. >>> a1 = Article(headline='Django lets you build Web apps easily')  


只有把它保存了,才能把它和出版社关联在一起。否则会出错如下:

  1. >>> a1.publications.add(p1)  
  2. Traceback (most recent call last):  
  3. ...  
  4. ValueError: 'Article' instance needs to have a primary key value before a many-to-many relationship  can be used.  



保存。

  1. >>> a1.save()  


关联文章和出版社。



建立第2篇文章,让它在两个出版社中出现。

  1. >>> a2 = Article(headline='NASA uses Python')  
  2. >>> a2.save()  
  3. >>> a2.publications.add(p1, p2)  
  4. >>> a2.publications.add(p3)  


再次添加也OK

  1. >>> a2.publications.add(p3)  


如果添加错误类型的对象会发生 TypeError:

  1. >>> a2.publications.add(a1)  
  2. Traceback (most recent call last):  
  3. ...  
  4. TypeError: 'Publication' instance expected  


使用create()一次创建并把出版社指派到一篇文章:

  1. >>> new_publication = a2.publications.create(title='Highlights for Children')  


文章对象有权访问和它们相关联的出版社对象(物件):


  1. >>> a1.publications.all()  
  2. [<Publication: The Python Journal>]  
  3. >>> a2.publications.all()  
  4. [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]  


出版社对象也有权访问与它们相关联的文章对象:

  1. >>> p2.article_set.all()  
  2. [<Article: NASA uses Python>]  
  3. >>> p1.article_set.all()  
  4. [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]  
  5. >>> Publication.objects.get(id=4).article_set.all()  
  6. [<Article: NASA uses Python>]  


使用  lookups across relationships 来query多对多关系:

  1. >>> Article.objects.filter(publications__id__exact=1)  
  2. [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]  
  3. >>> Article.objects.filter(publications__pk=1)  
  4. [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]  
  5. >>> Article.objects.filter(publications=1)  
  6. [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]  
  7. >>> Article.objects.filter(publications=p1)  
  8. [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]  
  9.   
  10. >>> Article.objects.filter(publications__title__startswith="Science")  
  11. [<Article: NASA uses Python>, <Article: NASA uses Python>]  
  12.   
  13. >>> Article.objects.filter(publications__title__startswith="Science").distinct()  


count()函数与distinct()表现相同:

  1. >>> Article.objects.filter(publications__title__startswith="Science").count()  
  2. 2  
  3.   
  4. >>> Article.objects.filter(publications__title__startswith="Science").distinct().count()  
  5. 1  
  6.   
  7. >>> Article.objects.filter(publications__in=[1,2]).distinct()  
  8. [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]  
  9. >>> Article.objects.filter(publications__in=[p1,p2]).distinct()  
  10. [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]  


反向 m2m查询也被支持(如,开始的表格没有 ManyToManyField):

  1. >>> Publication.objects.filter(id__exact=1)  
  2. [<Publication: The Python Journal>]  
  3. >>> Publication.objects.filter(pk=1)  
  4. [<Publication: The Python Journal>]  
  5.   
  6. >>> Publication.objects.filter(article__headline__startswith="NASA")  
  7. [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]  
  8. >>> Publication.objects.filter(article__id__exact=1)  
  9. [<Publication: The Python Journal>]  
  10. >>> Publication.objects.filter(article__pk=1)  
  11. [<Publication: The Python Journal>]  
  12. >>> Publication.objects.filter(article=1)  
  13. [<Publication: The Python Journal>]  
  14. >>> Publication.objects.filter(article=a1)  
  15. [<Publication: The Python Journal>]  
  16. >>> Publication.objects.filter(article__in=[1,2]).distinct()  
  17. [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]<p></p><p>>>> Publication.objects.filter(article__in=[a1,a2]).distinct()  
  18. [<Publication: Highlights for Children>, <Publication: Science News>, <Publication>, <Publication: Science Weekly>, <Publication: The Python Journal>]</p>  



也可以按自己预期的那样排除一个相关的项目(尽管使用的SQL语句有一点复杂):

  1. >>> Article.objects.exclude(publications=p2)  
  2. [<Article: Django lets you build Web apps easily>]  


如果我们删除一个出版社,那么它的文章就不能够被访问:

  1. >>> p1.delete()  
  2. >>> Publication.objects.all()  
  3. [<Publication: Highlights for Children>, <Publication: Science News>,  <Publication: Science Weekly>]  
  4. >>> a1 = Article.objects.get(pk=1)  
  5. >>> a1.publications.all()  
  6. []  

如果我们删除一篇文章,则它的出版社也不能访问它:

  1. >>> a2.delete()  
  2. >>> Article.objects.all()  
  3. [<Article: Django lets you build Web apps easily>]  
  4. >>> p2.article_set.all()  
  5. []  


经由m2m的另一方法来添加:

  1. >>> a4 = Article(headline='NASA finds intelligent life on Earth')  
  2. >>> a4.save()  
  3. >>> p2.article_set.add(a4)  
  4. >>> p2.article_set.all()  
  5. [<Article: NASA finds intelligent life on Earth>]  
  6. >>> a4.publications.all()  
  7. [<Publication: Science News>]  



经由关键字的另一方法添加:

  1. >>> new_article = p2.article_set.create(headline='Oxygen-free diet works wonders')  
  2. >>> p2.article_set.all()  
  3. [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet  works wonders>]  
  4. >>> a5 = p2.article_set.all()[1]  
  5. >>> a5.publications.all()  
  6. [<Publication: Science News>]  



从文章中移除出版社:

  1. >>> a4.publications.remove(p2)  
  2. >>> p2.article_set.all()  
  3. [<Article: Oxygen-free diet works wonders>]  
  4. >>> a4.publications.all()  
  5. []  



从出版社中移除文章:

  1. >>> p2.article_set.remove(a5)  
  2. >>> p2.article_set.all()  
  3. []  
  4. >>> a5.publications.all()  
  5. []  



关系集合可以被分配。分配时所有已经存在的集合成员会被清除:

  1. >>> a4.publications.all()  
  2. [<Publication: Science News>]  
  3. >>> a4.publications = [p3]  
  4. >>> a4.publications.all()  
  5. [<Publication: Science Weekly>]  


关系集合可以清除:

  1. >>> p2.article_set.clear()  
  2. >>> p2.article_set.all()  
  3. []  


而且你也可以从另一端清除(注:关系的另一端):

  1. >>> p2.article_set.add(a4, a5)  
  2. >>> p2.article_set.all()  
  3. [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]  
  4. >>> a4.publications.all()  
  5.   
  6. [<Publication: Science News>, <Publication: Science Weekly>]  
  7.   
  8. >>> a4.publications.clear()  
  9.   
  10. >>> a4.publications.all()  
  11.   
  12. []  
  13.   
  14. >>> p2.article_set.all()  
  15.   
  16. [<Article: Oxygen-free diet works wonders>]  


重建我们删除过的文章和出版社:

  1. >>> p1 = Publication(title='The Python Journal')  
  2. >>> p1.save()  
  3. >>> a2 = Article(headline='NASA uses Python')  
  4. >>> a2.save()  
  5. >>> a2.publications.add(p1, p2, p3)  



批量删除一些出版社-引用的被删出版社应当去掉:

  1. >>> Publication.objects.filter(title__startswith='Science').delete()  
  2. >>> Publication.objects.all()  
  3. >>> Article.objects.all()  
  4. [<Article: Django lets you build Web apps easily>, <Article: NASA finds intelligent life on Earth>, <Article: NASA uses Python>,<Article: Oxygen-free diet works wonders>]  
  5. >>> a2.publications.all()  
  6. [<Publication: The Python Journal>]  

批量删除一些文章-引用的被删除对象应当去掉:

  1. >>> q = Article.objects.filter(headline__startswith='Django')  
  2. >>> print(q)  
  3. [<Article: Django lets you build Web apps easily>]  
  4. >>> q.delete()  


在delete()以后,QuerySet缓存需要清理,而且引用对象应该被去掉:

  1. >>> print(q)  
  2. []  
  3. >>> p1.article_set.all()  
  4. [<Article: NASA uses Python>]  



除了调用clear()之外,可以赋值一个空的集合:

  1. >>> p1.article_set = []  
  2. >>> p1.article_set.all()  
  3. []  
  4.   
  5. >>> a2.publications = [p1, new_publication]  
  6. >>> a2.publications.all()  
  7. [<Publication: Highlights for Children>, <Publication: The Python  Journal>]  
  8. >>> a2.publications = []  
  9. >>> a2.publications.all()  
  10. []  


附:

The Django Book中的1个例子。

按部就班照着它做,没看到它写如何添加Book。


model.py类

  1. #coding=utf-8  
  2. from django.db import models  
  3.   
  4. class Publisher(models.Model):  
  5.     name=models.CharField(max_length=30)  
  6.     address=models.CharField(max_length=50)  
  7.     city=models.CharField(max_length=60)  
  8.     state_province=models.CharField(max_length=30)  
  9.     country=models.CharField(max_length=50)  
  10.     website=models.URLField()  
  11.     def __unicode__(self):  
  12.         return self.name  
  13.   
  14.     class Meta:  
  15.         ordering=['name']  
  16.       
  17. class Author(models.Model):  
  18.     first_name=models.CharField(max_length=100)  
  19.     last_name=models.CharField(max_length=40)  
  20.     email=models.EmailField(max_length=40,verbose_name='email_address',blank=True)  
  21.     def __unicode__(self):  
  22.         return u'%s %s' % (self.first_name,self.last_name)  
  23.       
  24. class Book(models.Model):  
  25.     title=models.CharField(max_length=100)  
  26.     authors=models.ManyToManyField(Author)  
  27.     publisher=models.ForeignKey(Publisher)  
  28.     publication_date=models.DateField()  
  29.     def __unicode__(self):  
  30.         return  


生成的表是(这里使用mysql):

表中字段为:






setting.py中installed app要加上mysite.books。

cmd进入命令行,在站点下运行命令:

  1. I:mysite>manage.py shell  


  1. >>>from mysite.books.models import Publisher,Author,Book  
  2. >>>import datetime  
  3. >>>b1=Book(title='Beginer osf Labview',publisher=Publisher.objects.all()[1],publication_date=datetime.datetime.strptime('20130726','%Y%m%d'))  
  4. >>>b1.save()  #保存一下,得到一个book的ID  
  5. >>>b1.authors.add(Author.objects.all()[1])  
  6. >>>b1<Book: Beginer osf Labview>>>> Book.objects.all()[<Book: Learn C>, <Book: Learn Python>, <Book: Beginer osf Labview>]  

b1在新建时,需要把出版社和日期都包含进来。否则会出错:

  1. >>>b2=Book()  
  2. >>>b2.save()  
  3. IntegrityError: (1048, "Column 'publisher_id' cannot be null")  


在Book类中可以看到Publisher是外键,在表中会有一个publisher_id不允许为空。

而对于ManyToMany字段,Book中的Author只能使用add方法来添加,添加之前需要通过save()取得一个book的id。

Add以后,不用再次save,也可以保存到数据库?疑问

原文地址:https://www.cnblogs.com/yunsicai/p/3897421.html