python - django 模型中one-to-many和foreign key不是特别能够理解?

 顺顺当当的小屋约_564 发布于 2022-11-05 22:44

在《The Django Book》中有这么一个实例描述

我们来假定下面的这些概念、字段和关系:

  • 一个作者有姓,有名及email地址。
  • 出版商有名称,地址,所在城市、省,国家,网站。
  • 书籍有书名和出版日期。 它有一个或多个作者(和作者是多对多的关联关系[many-to-many]), 只有一个出版商(和出版商是一对多的关联关系[one-to-many],也被称作外键[foreign key])

它说,书籍出版商的关系是一对多,OneToMany(也叫外键,ForeignKey),这个我就觉得没法理解,在我看来,一本书应该只能属于一个出版商,一个出版商可以出多本书。从字面上理解,应该是ManyToOne

然后对应到models,The Django Book 是这么写的,只在Book 这个模型中注明了外键

class Book(models.Model):
    title = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)
    publisher = models.ForeignKey(Publisher)  '''here!'''
    publication_date = models.DateField()

但是以之前字面上的理解,我觉得应该是在出版商那个模型上为book增加ForeignKey(OneToMany)啊...


'''这是我的理解,但是应该是错的...'''

class Publisher(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60)
    state_province = models.CharField(max_length=30)
    country = models.CharField(max_length=50)
    book = models.ForeignKey(Book) '''here'''
    website = models.URLField()
2 个回答
  • LZ,Django官方所说的one-to-many只是它的写法而已,不具有指向性。更明确的是外键这种叫法。
    如果按照你所理解的具有指向性,那么就要写成one-to-many和many-to-one了。
    但要注意:one-to-one和foreignkey(unique=True)两种确实有指向性,至少在调用的时候会有这种差别。

    2022-11-12 01:48 回答
  • 应该是翻译上的不准确。

    We’ll suppose the following concepts, fields, and relationships:

    An author has a first name, a last name and an email address. A publisher has a name, a street address, a city, a state/province, a country, and a Web site. A book has a title and a publication date. It also has one or more authors (a many-to-many relationship with authors) and a single publisher (a one-to-many relationship – aka foreign key – to publishers).

    http://www.djangobook.com/en/2.0/chapter05.html

    Django 总共定义了三种关系

    • one-to-one
    • one-to-many
    • many-to-many

    这里的关系的表述并非单向的。book 和 publisher 之间有一个one-to-many的关系,但是其中的one是publisher,many是book。这种关系的具体实现方法是在book中加入一个foreign key。

    2022-11-12 01:48 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有