在djang中使用update_或_create时,重复的键值违反了唯一约束错误

2024-09-28 03:14:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我的型号:

class DirectoryDoctors (models.Model):
    num = models.AutoField(primary_key=True)
    name = models.CharField(max_length=100)
    design_choices = (
        ('IMO', 'IMO'),
        ('AIMO', 'AIMO'),
    )
    designation = models.CharField(
        choices=design_choices, max_length=30, default='unspecified')
    mobile = models.CharField(max_length=15, default='')
    alternate = models.CharField(max_length=15, default='', blank=True)
    email = models.CharField(max_length=50, default='', blank=True)
    dob = models.DateField(null=True, blank=True)
    specialiast_or_not_choices = (
        ('Yes', 'Yes'),
        ('No', 'No'),
        ('Unspecified', 'Unspecified')
    )
    specialiast = models.CharField(
        choices=specialiast_or_not_choices, max_length=30, default='Unspecified')
    specialty_choices = (
        ('Internal Medicine', 'Internal Medicine'),
        ('General Surgery', 'General Surgery'),
        ('Not Applicable', 'Not Applicable')
    )
    specialty = models.CharField(
        choices=specialty_choices, max_length=30, default='Unspecified')
    institution = models.ForeignKey(DirectoryHospital, on_delete=models.DO_NOTHING)
    bloodgroup_choices = (('apos', 'A+'),
        ('-', '-')
        )
    bloodgroup = models.CharField(choices=bloodgroup_choices, max_length=15, default='-', blank=True)

    spousename = models.CharField(max_length=100, blank=True)
    children = models.CharField(max_length=200, blank=True)
    present_address = models.CharField(max_length=200, blank=True)
    permanent_address = models.CharField(max_length=200, blank=True)


    class Meta:
        unique_together = ["name", "mobile", "email"]

    def __str__(self):
        st = f"{self.name}, {self.designation}, {self.institution}"
        return st

以及更新数据时的代码:

^{pr2}$

为什么会这样?我该怎么解决这个问题?在

这里已经询问了一个similiar question,但在这一点上,问题显然是由于在update_或\u create中使用defaults参数造成的。我觉得这不适用于我的情况,尽管最终结果是相同的错误


Tags: nameselftruedefaultmodelslengthmaxclass

热门问题