Django many-to-many relationalships

2015-05-25

Many-to-many relationalships

这篇是 Django 文档中的一些例子,在 tutorial 中没有全部展示的东西看例子很容易就明白了,这里我就大概翻译一下,也作为自己的一个笔记。

models.py

多对多关系,是在模型中用 ManyToManyField 定义。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from django.db import models

class Publication(models.Model):
title = models.CharField(max_length = 30)

def __str__(self):
return self.title

class Meta:
ordering = ('title',) # 这里是单元素元组请注意,有一个逗号

class Article(models.Model):
headline = models.CharField(max_length = 100)
publications = models.ManyToManyField(Publication)

def __str__(self):
return self.headline

class Meta:
ordering = ('headline',) # 同样是单元素元组请注意逗号

Article 是一张表,有 headlinepublication 两个字段,publication 字段对应 Publication 这张表,多对多关系,One Article can have mutiple Publication and one Publication can have Mutiple Publication。下面就是演示 python manage.py shell 中的 API 用法:

python manage.py shell API 用法

实例化 Publication 对象,save() 存到数据库中

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

实例化 Article,与 Publicaton 联系起来

1
2
3
>>> a1 = Article(headline = "Django let's you build Web apps easily")
>>> a1.save()
>>> a1.piblications.add(p1)

这里把前面实例化的三个 Publication 全部加到 a2 中了

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

重复添加也没有问题

1
>>> a.publication.add(p3)

实例化 Article 的同时添加 Publication

1
>>> new_publication = a2.publication.create(title = "Highlings for Children")

查看每个 Article 对应的 Publication

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

也可通过 Publication 关联的 Article 查看,QuerySet 对象

1
2
3
4
5
6
>>> 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>]

然后就是各种 API,增删改查,没什么多说的,摸索两下就知道怎么用了

1
2
3
4
>>> Article.objects.filter(id = 1)
>>> Article.objects.filter(pk = 1)
>>> Article.objects.filter(publications=1)
>>> Article.objects.filter(publications=p1)