Django中表关系有点不明白

2013-09-25 16:29:37 +08:00
 favormm
from django.db import models

class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')

class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()


这样的两张表,ForeignKey是一对多的关系,还是多对一的关系?
p = Poll(question="What's new?", pub_date=timezone.now())
p.save()
这两句表示插入一条Poll的数据。

p.choice_set.create(choice='Not much', votes=0) 为何表示插入一条Choice的数据呢
p.choice_set表示一个集合,然后create是创建一个新的对象,为何这个对象是Choice?
为何是p.choice_set, p是Poll表的数据,为何可以.choice_set, 我认为同理也可以p.votes_set(可是我的猜想是错误的,votes不可以。)
2768 次点击
所在节点    问与答
2 条回复
glasslion
2013-09-25 17:42:19 +08:00
https://docs.djangoproject.com/en/dev/topics/db/queries/#related-objects

When you define a relationship in a model (i.e., a ForeignKey, OneToOneField, or ManyToManyField), instances of that model will have a convenient API to access the related object(s).

Using the models at the top of this page, for example, an Entry object e can get its associated Blog object by accessing the blog attribute: e.blog.

(Behind the scenes, this functionality is implemented by Python descriptors. This shouldn’t really matter to you, but we point it out here for the curious.)

Django also creates API accessors for the “other” side of the relationship – the link from the related model to the model that defines the relationship. For example, a Blog object b has access to a list of all related Entry objects via the entry_set attribute: b.entry_set.all().

Choice表里有到Poll的外键
favormm
2013-09-26 11:49:47 +08:00
@glasslion 感谢,终于明白了。


Poll是主表, Choice是子表,原因就是ForeignKey那句。主表默认有一个子表集的属性,命名默认为子表名小写加_set, 也可以手动指改命名。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/83647

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX