Djanog many-to-one relationships

2015-06-13

Many-to-one relationships

三个数据库 API 例子中的第二个,有时候分不清,多对一和一对多,现在有点分得清了,但是有些查询方面还是有点糊,QuerySet 这搞得,简单的查询很容易搞定,但是数据库模型设置的复杂了,或者要查询的东西复杂了,就搞不太明白了,而且基础的教程里面都没有讲,要自己去查文档。

我自己的应用模型实例

刚结合自己的应用的数据库模型,稍稍搞清了模型的多对一,一对多关系,先说在我自己的模型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Tag(models.Model):
tag_name = models.CharField(
default='读不下去', max_length=64, blank=True, null=True)

def __unicode__(self):
return self.tag_name


class Book_Info(models.Model):
# Book Info 14 objects in total. (Book cover didn't add yet)
isbn10 = models.CharField(default='', max_length=10, blank=True)
isbn13 = models.CharField(max_length=13)
title = models.CharField(max_length=128)

# My Customise Tags 想读、正在读、读过、!!! 读不下去!!!(独创标签,仅此一家!!!)
customise_tags = models.ForeignKey(Tag, blank=True, null=True)

def __unicode__(self):
return self.title


class Note(models.Model):
# Book Notes. You can take some notes for one book your owned.
book_info = models.ForeignKey(Book_Info, blank=True, null=True)
pages = models.IntegerField(blank=True, null=True)
notes = models.CharField(max_length=256, blank=True)

def __unicode__(self):
return self.notes

省略了一些没用的字段,Book_Info 这张表有一些基本的字段,都是 models.CharFieldcustomise_tag 这个字段和 Tag 这张表就是多对多的关系。Note 中定义了一个 book_info = models.ForeignKey(Book_Info, blank=True. null=True),这个就说明 Note 表中的 book_info 字段是 Note 表的外键,一个 Book_Info 可以对应多个 Note,一对多关系。

models.py

下面这个示例就是文档中的例子:

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 Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()

def __str__(self): # __unicode__ on Python 2
return "%s %s" % (self.first_name, self.last_name)

class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter)

def __str__(self): # __unicode__ on Python 2
return self.headline

class Meta:
ordering = ('headline',)

这个模型中,reporter 字段是 Article 表的外键,一个 Reporter 可以对应多个 Article,刚才一想,好像又不太对了……怎么老是要搞这个字面上的解释呢,看来这个数据库还得多看书,表和字段的抽象关系理不怎么清啊。

python manage.py shell API 用法

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

1
2
3
4
5
>>> r = Reporter(first_name='John', last_name='Smith', email='john@example.com')
>>> r.save()

>>> r2 = Reporter(first_name='Paul', last_name='Jones', email='paul@example.com')
>>> r2.save()

实例化 Article,将已经实例化的 Reporter 对象绑定到 Article

1
2
3
4
5
6
7
8
9
>>> from datetime import date
>>> a = Article(id=None, headline="This is a test", pub_date=date(2005, 7, 27), reporter=r)
>>> a.save()

>>> a. reporter.id
1

>>> a.reporter
<Reporter: John Smith>

绑定外键关系之前必须要保存对象,Django 1.8 前这么做会触发 ValueError 异常,1.8 之后不会触发异常,数据静默丢失。

Article 对象获得 Reporter 对象

1
2
3
>>> r = a.reporter
>>> r.first_name, r.last_name
('John', 'Smith')

Reporter 对象实例化 Article 对象,直接将实例化的 Article 绑定到已实例化 Reporter 对象中

1
2
3
4
5
6
7
>>> new_article = r.article_set.create(headline="John's second story", pub_date=date(2005, 9, 29))
>>> new_article
<Article: John's second story>
>>> new_article.reporter
<Reporter: John Smith>
>>> new_article.reporter.id
1

先实例化 Article 对象,再通过 article_set.add 绑定 Reporter 对象

1
2
3
4
5
6
7
>>> new_article2 = Article(headline="Paul's story", pub_date=date(2006, 1, 17))
>>> r.article_set.add(new_article2)
>>> new_article2.reporter
<Reporter.reporter.id>
1
>>> r.article_set.all()
[<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]

绑定上面同一个 Article 对象到不同的 Reporter 对象中,它就变了

1
2
3
4
5
>>> r2.article_set.add(new_article2)
>>> new_article2.reporter.id
2
>>> new_article2.reporter
<Reporter: Paul Jones>

原来 new_article2reporterr <Reporter: John Smith>,现在变成了 <Reporter: Paul Jones>

绑定错误的对象就会引发异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> r.article_set.add(r2)
Traceback (most recent call last):
...
TypeError: 'Article' instance expected

>>> r.article_set.all()
[<Article: John's second story>, <Article: This is a test>]
>>> r2.article_set.all()
[<Article: Paul's story>]

>>> r.article_set.count()
2

>>> r2.article_set.count()
1

Reporter 对象绑定包另一个 Reporter 对象上会引发 TypeError 异常。

其他

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
>>> r.article_set.filter(headline__startswith='This')
>>> Article.objects.filter(reporter__first_name='John')

# filter 两个条件,转到 SQL 中就是 WHERE 和 AND 语句
>>> Article.objects.filter(reporter__first_name='John', reporter__last_name='Smith')
>>> Article.objects.filter(reporter__pk=1)
>>> Article.objects.filter(reporter=1)
>>> Article.objects.filter(reporter=r)
>>> Article.objects.filter(reporter__in=Reporter.objects.filter(first_name='John')).distinct()

# 下面三条语句的结果是一样的
>>> Reporter.objects.filter(article__pk=1)
>>> Reporter.objects.filter(article=1)
>>> Reporter.objects.filter(article=a)
[<Reporter: John Smith>]

>>> Reporter.objects.filter(article__headline__startswith='This')
[<Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>]
>>> Reporter.objects.filter(article__headline__startswith='This').distinct()
[<Reporter: John Smith>]

>>> Reporter.objects.filter(article__headline__startswith='This').count()
3
>>> Reporter.objects.filter(article__headline__startswith='This').distinct().count()
1

>>> Reporter.objects.filter(article__reporter__first_name__startswith='John')
[<Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>]
>>> Reporter.objects.filter(article__reporter__first_name__startswith='John').distinct()
[<Reporter: John Smith>]
>>> Reporter.objects.filter(article__reporter=r).distinct()
[<Reporter: John Smith>]

>>> Reporter.objects.filter(article__headline__startswith='This').delete()
>>> Reporter.objects.all()
[]
>>> Article.objects.all()
[]