【问题标题】:M2M relationship or 2 FKs?M2M 关系还是 2 个 FK?
【发布时间】:2012-05-25 06:12:02
【问题描述】:

以下哪种结构更可取:

# M2M
class UserProfile(models.Model):
    ...
    groups = models.ManyToManyField(Group)

class Group(models.Model):
    ...

或 -

# 2 FKs
class UserProfile(models.Model):
    ...

class Group(models.Models):
    ...

class GroupMember(models.Model):
    user = models.ForeignKey(UserProfile)
    group = models.ForeignKey(Group)

哪个更好?

【问题讨论】:

    标签: mysql sql django


    【解决方案1】:

    您也可以使用through 选项组合这两种变体

    groups = models.ManyToManyField(Group, through='GroupMember')
    

    better 是什么意思?通常不需要创建中间模型(必须存储extra data的情况除外)。

    ManyToManyField 完美地完成了他的工作,所以不要自己编写它的功能。

    【讨论】:

      【解决方案2】:

      两者本质上是一样的。当您执行 M2M 时,Django 会自动创建一个中间模型,这与您的 GroupMember 模型非常完全。但是,它还设置了一些 API 挂钩,使您可以直接从 UserProfile 模型访问 Group 模型,而不必弄乱中间模型。

      您可以使用@San4ez 解释的through 重新添加相同的钩子,但您只会让事情变得更复杂。仅当您需要向关系中添加其他字段时,创建自定义 through 模型才有用。否则,请坚持使用默认值。

      长短不一,#1更好,只是因为它和#2完全一样,但更简单,没有多余的代码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-08
        • 1970-01-01
        • 2018-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-25
        相关资源
        最近更新 更多