【问题标题】:Assigning a value to a ManyToManyField [duplicate]为ManyToManyField赋值[重复]
【发布时间】:2017-03-23 07:19:22
【问题描述】:

这是我第一次在 Django 中使用多对多关系。这就是我想要完成的:

我有一个患者模型 modelPatient 可以分配给多个学生(医学生),每个学生 modelStudent 可以检查多个患者。

为此,我决定在这里使用多对多关系:

class modelPatient(models.Model):
    student = models.ManyToManyField(modelStudent,null=True,default=None,blank=True)
    patient_name = models.CharField(max_length=128, unique=False)

这是学生模型:

class modelStudent(models.Model):
    first_name = models.CharField(max_length=128, unique=False)

现在假设我正在做这样的事情:

patient = modelPatient.object.get(patient_name="John")

如何将此patient 分配给多个学生studentA 和studentB?

studentA = modelStudent.objects.get(first_name="john")
studentB = modelStudent.objects.get(first_name="adam")

我想要的是将patient 实例与studentA 和studentB 相关联。请让我知道这是否可行或我的设计决定是否不正确。

【问题讨论】:

  • 啊,所以patient.student.add(studentA) ?
  • 我不确定这是否是正确的设计决策

标签: django django-models many-to-many


【解决方案1】:

https://docs.djangoproject.com/en/1.10/topics/db/examples/many_to_many/

patient = modelPatient.object.get(patient_name="John")
studentA = modelStudent.objects.get(first_name="john")
studentB = modelStudent.objects.get(first_name="adam")
patient.student.add(studentA, studentB)

另外,关于modelPatient - model 以及patient_name 中的patient 是多余的,仅供参考。您已经在 Patient 模型命名空间中执行此操作

【讨论】:

    【解决方案2】:

    可以在这里找到答案:how to add data into ManyToManyField?

    只需将它们添加到您的关系中:

    patient.student.add(studentA)
    patient.student.add(studentB)
    

    或者您可以将它们都添加到一行中

    patient.student.add(studentA, studentB)
    

    有关更多信息,请参阅文档,其中提供了非常好的示例:https://docs.djangoproject.com/en/1.10/topics/db/examples/many_to_many/

    另外请记住,您可以从student 对象访问patient。

    【讨论】:

      猜你喜欢
      • 2019-02-09
      • 2013-02-01
      • 2019-11-05
      • 2021-03-30
      • 2012-08-31
      • 2016-03-08
      • 1970-01-01
      • 2019-02-06
      • 2012-03-15
      相关资源
      最近更新 更多