favormm
V2EX  ›  问与答

Django中表关系有点不明白

  •  
  •   favormm · Sep 25, 2013 · 3225 views
    This topic created in 4613 days ago, the information mentioned may be changed or developed.
    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 replies    1970-01-01 08:00:00 +08:00
    glasslion
        1
    glasslion  
       Sep 25, 2013
    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
       Sep 26, 2013
    @glasslion 感谢,终于明白了。


    Poll是主表, Choice是子表,原因就是ForeignKey那句。主表默认有一个子表集的属性,命名默认为子表名小写加_set, 也可以手动指改命名。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3303 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 12:33 · PVG 20:33 · LAX 05:33 · JFK 08:33
    ♥ Do have faith in what you're doing.