V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
favormm
V2EX  ›  问与答

Django中表关系有点不明白

  •  
  •   favormm · 2013-09-25 16:29:37 +08:00 · 2768 次点击
    这是一个创建于 4075 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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不可以。)
    2 条回复    1970-01-01 08:00:00 +08:00
    glasslion
        1
    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
        2
    favormm  
    OP
       2013-09-26 11:49:47 +08:00
    @glasslion 感谢,终于明白了。


    Poll是主表, Choice是子表,原因就是ForeignKey那句。主表默认有一个子表集的属性,命名默认为子表名小写加_set, 也可以手动指改命名。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1030 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 19:38 · PVG 03:38 · LAX 11:38 · JFK 14:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.