python - 具有 2 个 m2m 关系的数据库设计

标签 python database django database-design

我想要一些关于如何进一步开发我的模型和表格的建议。

这个模型目前允许我保存链接到 m2m 关系中的疾病和状态的选项。如果我想保存结果及其与状态、疾病和选项相关的相关值,我将如何进一步构建它?

例如,结果将具有与之关联的特定选项。选项将是一个特定的状态,该状态将与特定的疾病相关联。对于与特定选项相关联的每个结果,都会为其分配一个值。

我认为我需要一个中间表,因为用户将分配给它的结果值。我对如何将结果链接到选项感到困惑,因为选项是 m2m。

class Option(models.Model):
    disease = models.ForeignKey(Disease)
    option = models.CharField(max_length=300)

class Outcome(models.Model):      
   disease = models.ForeignKey(Disease)
   outcome = models.CharField(max_length=200)

class DiseaseState(models.Model):
   state = models.CharField(max_length=300)
   disease = models.ForeignKey(Disease)
   option = models.ManyToManyField(Option, blank=True)
   #outcome = models.ManyToManyField(Outcome, blank=True) #will adding this solve my use case? It does not seem like outcome will link to option.

更新:

为了清楚起见:一种疾病有一种疾病状态。 DiseaseState 有一个选项。一个选项有结果。结果具有分配给它的值。 Option 和 Outcomes 都是列表,用户可以从列表中进行选择。

最佳答案

我不完全确定我是否遵循,但您在这里有几个选择。

首先是手动创建Outcome和DiseaseState之间的中间表

class DiseaseStateOutcome(models.Model):
    unique_together = (('disease_state', 'outcome'),)

    disease_state = models.ForeignKey(DiseaseState)
    outcome = models.ForeignKey(Outcome)

    #option foreign key, or m2m relation to option here

您的另一个选择是,如果您只想要与 DiseaseState/Outcome 对相关的单个选项,则只需将 ForeignKey 从 Outcome 放入 Option。

class Outcome(models.Model):
    #Your other fields here
    option = models.ForeignKey(Option)

关于python - 具有 2 个 m2m 关系的数据库设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18386446/

相关文章:

python - 比较 Python 字典和嵌套字典

Python 无法使用 urllib2 进行 PUT

mysql 带条件的 TableView

django - 在 Django 模板中定义 "global variable"

python - 安装 Django : Using XAMPP's MySQL, MySQL-python 1.2.3 和 1.2.4 错误?

python - 根据 django 网站上的操作显示用户上个月的进度

python - 重复插入数据库表

sql - 有没有办法在不执行未知数据库查询的情况下获取类型/名称?

sql - 外键困惑

django - 从运行服务器迁移到生产服务器