django manytomany
转载:http://my.oschina.net/u/572994/blog/105280
例如有如下模型
models.py
|
1
2
3
4
5
6
7
|
from django.db import modelsclass 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 modelsclass 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)
本例中,一篇文章可以被很多出版社发表,而一个出版社也会发表多个文章。
- from django.db import models
- class Publication(models.Model):
- title = models.CharField(max_length=30)
- # On Python 3: def __str__(self):
- def __unicode__(self):
- return self.title
- class Meta:
- ordering = ('title',)
- class Article(models.Model):
- headline = models.CharField(max_length=100)
- publications = models.ManyToManyField(Publication)
- # On Python 3: def __str__(self):
- def __unicode__(self):
- return self.headline
- class Meta:
- ordering = ('headline',)
接下来我们使用Python API 功能执行操作的例子。
创建两个出版社:
- >>> p1 = Publication(title='The Python Journal')
- >>> p1.save()
- >>> p2 = Publication(title='Science News')
- >>> p2.save()
- >>> p3 = Publication(title='Science Weekly')
- >>> p3.save()
新建一个文章:
- >>> a1 = Article(headline='Django lets you build Web apps easily')
只有把它保存了,才能把它和出版社关联在一起。否则会出错如下:
- >>> a1.publications.add(p1)
- Traceback (most recent call last):
- ...
- ValueError: 'Article' instance needs to have a primary key value before a many-to-many relationship can be used.
保存。
- >>> a1.save()
关联文章和出版社。
建立第2篇文章,让它在两个出版社中出现。
- >>> a2 = Article(headline='NASA uses Python')
- >>> a2.save()
- >>> a2.publications.add(p1, p2)
- >>> a2.publications.add(p3)
再次添加也OK
- >>> a2.publications.add(p3)
如果添加错误类型的对象会发生 TypeError:
- >>> a2.publications.add(a1)
- Traceback (most recent call last):
- ...
- TypeError: 'Publication' instance expected
使用create()一次创建并把出版社指派到一篇文章:
- >>> new_publication = a2.publications.create(title='Highlights for Children')
文章对象有权访问和它们相关联的出版社对象(物件):
- >>> a1.publications.all()
- [<Publication: The Python Journal>]
- >>> a2.publications.all()
- [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
出版社对象也有权访问与它们相关联的文章对象:
- >>> p2.article_set.all()
- [<Article: NASA uses Python>]
- >>> p1.article_set.all()
- [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
- >>> Publication.objects.get(id=4).article_set.all()
- [<Article: NASA uses Python>]
使用 lookups across relationships 来query多对多关系:
- >>> Article.objects.filter(publications__id__exact=1)
- [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
- >>> Article.objects.filter(publications__pk=1)
- [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
- >>> Article.objects.filter(publications=1)
- [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
- >>> Article.objects.filter(publications=p1)
- [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
- >>> Article.objects.filter(publications__title__startswith="Science")
- [<Article: NASA uses Python>, <Article: NASA uses Python>]
- >>> Article.objects.filter(publications__title__startswith="Science").distinct()
count()函数与distinct()表现相同:
- >>> Article.objects.filter(publications__title__startswith="Science").count()
- 2
- >>> Article.objects.filter(publications__title__startswith="Science").distinct().count()
- 1
- >>> Article.objects.filter(publications__in=[1,2]).distinct()
- [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
- >>> Article.objects.filter(publications__in=[p1,p2]).distinct()
- [<Article: Django lets you build Web apps easily>, <Article: NASA uses Python>]
反向 m2m查询也被支持(如,开始的表格没有 ManyToManyField):
- >>> Publication.objects.filter(id__exact=1)
- [<Publication: The Python Journal>]
- >>> Publication.objects.filter(pk=1)
- [<Publication: The Python Journal>]
- >>> Publication.objects.filter(article__headline__startswith="NASA")
- [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>, <Publication: The Python Journal>]
- >>> Publication.objects.filter(article__id__exact=1)
- [<Publication: The Python Journal>]
- >>> Publication.objects.filter(article__pk=1)
- [<Publication: The Python Journal>]
- >>> Publication.objects.filter(article=1)
- [<Publication: The Python Journal>]
- >>> Publication.objects.filter(article=a1)
- [<Publication: The Python Journal>]
- >>> Publication.objects.filter(article__in=[1,2]).distinct()
- [<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()
- [<Publication: Highlights for Children>, <Publication: Science News>, <Publication>, <Publication: Science Weekly>, <Publication: The Python Journal>]</p>
也可以按自己预期的那样排除一个相关的项目(尽管使用的SQL语句有一点复杂):
- >>> Article.objects.exclude(publications=p2)
- [<Article: Django lets you build Web apps easily>]
如果我们删除一个出版社,那么它的文章就不能够被访问:
- >>> p1.delete()
- >>> Publication.objects.all()
- [<Publication: Highlights for Children>, <Publication: Science News>, <Publication: Science Weekly>]
- >>> a1 = Article.objects.get(pk=1)
- >>> a1.publications.all()
- []
如果我们删除一篇文章,则它的出版社也不能访问它:
- >>> a2.delete()
- >>> Article.objects.all()
- [<Article: Django lets you build Web apps easily>]
- >>> p2.article_set.all()
- []
经由m2m的另一方法来添加:
- >>> a4 = Article(headline='NASA finds intelligent life on Earth')
- >>> a4.save()
- >>> p2.article_set.add(a4)
- >>> p2.article_set.all()
- [<Article: NASA finds intelligent life on Earth>]
- >>> a4.publications.all()
- [<Publication: Science News>]
经由关键字的另一方法添加:
- >>> new_article = p2.article_set.create(headline='Oxygen-free diet works wonders')
- >>> p2.article_set.all()
- [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]
- >>> a5 = p2.article_set.all()[1]
- >>> a5.publications.all()
- [<Publication: Science News>]
从文章中移除出版社:
- >>> a4.publications.remove(p2)
- >>> p2.article_set.all()
- [<Article: Oxygen-free diet works wonders>]
- >>> a4.publications.all()
- []
从出版社中移除文章:
- >>> p2.article_set.remove(a5)
- >>> p2.article_set.all()
- []
- >>> a5.publications.all()
- []
关系集合可以被分配。分配时所有已经存在的集合成员会被清除:
- >>> a4.publications.all()
- [<Publication: Science News>]
- >>> a4.publications = [p3]
- >>> a4.publications.all()
- [<Publication: Science Weekly>]
关系集合可以清除:
- >>> p2.article_set.clear()
- >>> p2.article_set.all()
- []
而且你也可以从另一端清除(注:关系的另一端):
- >>> p2.article_set.add(a4, a5)
- >>> p2.article_set.all()
- [<Article: NASA finds intelligent life on Earth>, <Article: Oxygen-free diet works wonders>]
- >>> a4.publications.all()
- [<Publication: Science News>, <Publication: Science Weekly>]
- >>> a4.publications.clear()
- >>> a4.publications.all()
- []
- >>> p2.article_set.all()
- [<Article: Oxygen-free diet works wonders>]
重建我们删除过的文章和出版社:
- >>> p1 = Publication(title='The Python Journal')
- >>> p1.save()
- >>> a2 = Article(headline='NASA uses Python')
- >>> a2.save()
- >>> a2.publications.add(p1, p2, p3)
批量删除一些出版社-引用的被删出版社应当去掉:
- >>> Publication.objects.filter(title__startswith='Science').delete()
- >>> Publication.objects.all()
- >>> Article.objects.all()
- [<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>]
- >>> a2.publications.all()
- [<Publication: The Python Journal>]
批量删除一些文章-引用的被删除对象应当去掉:
- >>> q = Article.objects.filter(headline__startswith='Django')
- >>> print(q)
- [<Article: Django lets you build Web apps easily>]
- >>> q.delete()
在delete()以后,QuerySet缓存需要清理,而且引用对象应该被去掉:
- >>> print(q)
- []
- >>> p1.article_set.all()
- [<Article: NASA uses Python>]
除了调用clear()之外,可以赋值一个空的集合:
- >>> p1.article_set = []
- >>> p1.article_set.all()
- []
- >>> a2.publications = [p1, new_publication]
- >>> a2.publications.all()
- [<Publication: Highlights for Children>, <Publication: The Python Journal>]
- >>> a2.publications = []
- >>> a2.publications.all()
- []
附:
The Django Book中的1个例子。
按部就班照着它做,没看到它写如何添加Book。
model.py类
- #coding=utf-8
- from django.db import models
- class Publisher(models.Model):
- name=models.CharField(max_length=30)
- address=models.CharField(max_length=50)
- city=models.CharField(max_length=60)
- state_province=models.CharField(max_length=30)
- country=models.CharField(max_length=50)
- website=models.URLField()
- def __unicode__(self):
- return self.name
- class Meta:
- ordering=['name']
- class Author(models.Model):
- first_name=models.CharField(max_length=100)
- last_name=models.CharField(max_length=40)
- email=models.EmailField(max_length=40,verbose_name='email_address',blank=True)
- def __unicode__(self):
- return u'%s %s' % (self.first_name,self.last_name)
- class Book(models.Model):
- title=models.CharField(max_length=100)
- authors=models.ManyToManyField(Author)
- publisher=models.ForeignKey(Publisher)
- publication_date=models.DateField()
- def __unicode__(self):
- return
生成的表是(这里使用mysql):
表中字段为:
setting.py中installed app要加上mysite.books。
cmd进入命令行,在站点下运行命令:
- I:\mysite>manage.py shell
- >>>from mysite.books.models import Publisher,Author,Book
- >>>import datetime
- >>>b1=Book(title='Beginer osf Labview',publisher=Publisher.objects.all()[1],publication_date=datetime.datetime.strptime('20130726','%Y%m%d'))
- >>>b1.save() #保存一下,得到一个book的ID
- >>>b1.authors.add(Author.objects.all()[1])
- >>>b1<Book: Beginer osf Labview>>>> Book.objects.all()[<Book: Learn C>, <Book: Learn Python>, <Book: Beginer osf Labview>]
b1在新建时,需要把出版社和日期都包含进来。否则会出错:
- >>>b2=Book()
- >>>b2.save()
- IntegrityError: (1048, "Column 'publisher_id' cannot be null")
在Book类中可以看到Publisher是外键,在表中会有一个publisher_id不允许为空。
而对于ManyToMany字段,Book中的Author只能使用add方法来添加,添加之前需要通过save()取得一个book的id。
Add以后,不用再次save,也可以保存到数据库?
django manytomany的更多相关文章
- Django 之 ForeignKey、ManyToMany的访问方式
1.ForeignKey 情况I: from django.db import models class Blog(models.Model): pass class Entry(models.Mod ...
- Django的Many-to-Many(多对多)模型
Django的Many-to-Many(多对多)模型 日期:2012-05-05 | 来源:未知 | 作者:redice | 人围观 | 1 人鼓掌了! 鲲鹏Web数据抓取 - 专业Web ...
- Django基础四<二>(OneToMany和 ManyToMany,ModelForm)
上一篇博文是关于setting.py文件数据库的配置以及model与数据库表关系,实现了通过操作BlogUser,把BlogUser的信息存入后台数据库中.实际开发中有许多东西是相互联系的,除了数据的 ...
- Django实战(19):自定义many-to-many关系,实现Atom订阅
记得有人跟我说过,rails的has_many :through是一个”亮点“,在Django看来,该功能简直不值一提.rails中的many-to-many关联中,还需要你手工创建关联表(写 mig ...
- [py]django的manytomany字段和后台搜索过滤功能
我本来想搞下Django之select_related和prefetch_related的区别,看到这里有djangoapi的知识, 之前搞过django restfulapi,http://blog ...
- Django, one-to-many, many-to-many
1.定义关系 定义三个表,Publisher,Book,Author 一个作者有姓,有名及email地址. 出版商有名称,地址,所在城市.省,国家,网站. 书籍有书名和出版日期. 它有一个或多个作者( ...
- django如何用orm增加manytomany关系字段(自定义表名)
不自定义表名的,网上有现成的,但如果自定义之后,则要变通一下了. app_insert = App.objects.get(name=app_name) site_insert = Site.obje ...
- python django的ManyToMany简述
Django的多对多关系 在Django的关系中,有一对一,一对多,多对多的关系 我们这里谈的是多对多的关系 ==我们首先来设计一个用于示例的表结构== # -*- coding: utf-8 -*- ...
- manytomany django 正查, 反查
models from django.db import models from django.contrib.auth.models import User class GroupSheet(mod ...
随机推荐
- Android高手速成--第二部分 工具库
主要包括那些不错的开发库,包括依赖注入框架.图片缓存.网络相关.数据库ORM建模.Android公共库.Android 高版本向低版本兼容.多媒体相关及其他. 一.依赖注入DI 通过依赖注入减少Vie ...
- 【Alpha版本】冲刺阶段——Day 10
我说的都队 031402304 陈燊 031402342 许玲玲 031402337 胡心颖 03140241 王婷婷 031402203 陈齐民 031402209 黄伟炜 031402233 郑扬 ...
- android 项目中如何引入第三方jar包
http://www.360doc.com/content/13/0828/08/11482448_310390794.shtml
- .net 根据银行卡获取银行信息
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary ...
- touch移动触屏滑动事件
移动端触屏滑动的效果其实就是图片轮播,在PC的页面上很好实现,绑定click和mouseover等事件来完成.但是在移动设备上,要实现这种轮播的效果,就需要用到核心的touch事件.处理touch事件 ...
- popoverPresentationController UIPopoverController 使用方法详解
之前iPad特有的控件,现在iPhone亦可使用. 点击按钮,弹出popOverVC. 按钮的点击事件: - (IBAction)pickOrderAction:(UIButton *)sender ...
- 【DevOps】DevOps成功的八大炫酷工具
为自动化和分析所设计的软件及服务正加速devops改革的步伐,本文为你盘点了Devops成功的八大炫酷工具 Devops凭借其连接弥合开发与运营团队的能力正在各个行业呈现席卷之势.开发人员和运营人员历 ...
- 【GoLang】golang 中 defer 参数的蹊跷
参考资料: http://studygolang.com/articles/7994--Defer函数调用参数的求值 golang的闭包和普通函数调用区别:http://studygolang.com ...
- MVC前台页面做登录验证
最近接触了一个电商平台的前台页面,需要做一个登录验证,具体情况是:当用户想要看自己的订单.积分等等信息,就需要用户登录之后才能查询,那么在MVC项目中我们应该怎么做这个前台的验证呢? 1.我在Cont ...
- ORA-27101: shared memory realm does not exist
Oracle Error Tips by Burleson Consulting Oracle docs note this about ORA-27101: ORA-27101: shared me ...