如何从多个连接创建选择字段

时间:2017-12-22 08:59:26

标签: django

在我的Django模型中,我有很多连接。我还想从连接的诊断中选择一个主要诊断。

class Case(models.Model):
    diagnoses_all_icd_10 = models.ManyToManyField('ICD10')

如何创建仅显示相关诊断以供选择的选择字段?重要的是该解决方案也适用于Django管理员。

1 个答案:

答案 0 :(得分:1)

我认为through论证适合你。

https://docs.djangoproject.com/en/2.0/ref/models/fields/#django.db.models.ManyToManyField.through

在你的情况下:

class Case(models.Model):
    diagnoses_all_icd_10 = models.ManyToManyField(ICD10, through='DiagnoseOrder')

class DiagnoseOrder(models.Model):
    case = models.ForeignKey(Case, on_delete=models.CASCADE)
    icd_10 = models.ForeignKey(ICD10, on_delete=models.CASCADE)
    is_primary = models.BooleanField(default=False)

    def save(self, *args, **kwargs):
        # If not self.is_primary you won't need further query
        if self.is_primary:
            # Query if there is a primary order related to this case
            existing_primary = DiagnoseOrder.objects.filter(is_primary=True, case=self.case).first()
            if existing_primary:
                # You can change existing primary's status *up to your need
                existing_primary.is_primary = False
                existing_primary.save()
        super(DiagnoseOrder, self).save(*args, **kwargs)

然后,您可以使用InlineModelAdmin进行Django管理员自定义。

进一步阅读:

https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.StackedInline

https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.TabularInline