首页 > 解决方案 > 在 django 中使用 update_or_create 时重复键值违反唯一约束错误

问题描述

我的模型:

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

并在更新数据时编写代码:

dirhosp = DirectoryHospital.objects.get(name = disp, insttype = hospordisp, district = district)

try:
    dirdoc = DirectoryDoctors.objects.update_or_create(name = name, designation = desig, mobile = mob, alternate = alt, email = emailadd, dob = dob, specialiast = specialist_not, specialty = specialty, institution = dirhosp, bloodgroup = blgp, spousename = spouse, children = children, present_address = address_pres, permanent_address = address_perm)

    print(f"Saved name = {name}, designation = {desig}, mobile = {mob}, alternate = {alt}, email = {emailadd}, dob = {dob}, specialiast = {specialist_not}, specialty = {specialty}, institution = {dirhosp}, bloodgroup = {blgp}, spousename = {spouse}, children = {children}, present_address = {address_pres}, permanent_address = {address_perm}\n")
except Exception as e:                
    if "NaTType does not support utcoffset" in e.args[0]:
        dirdoc = DirectoryDoctors.objects.update_or_create(name = name, designation = desig, mobile = mob, alternate = alt, email = emailadd, specialiast = specialist_not, specialty = specialty, institution = dirhosp, bloodgroup = blgp, spousename = spouse, children = children, present_address = address_pres, permanent_address = address_perm)
        print("No proper DOB")
        print(f"Saved by alt: name = {name}, designation = {desig}, mobile = {mob}, alternate = {alt}, email = {emailadd}, specialiast = {specialist_not}, specialty = {specialty}, institution = {dirhosp}, bloodgroup = {blgp}, spousename = {spouse}, children = {children}, present_address = {address_pres}, permanent_address = {address_perm}\n")
    else:
        print("Another uncaught exception occured!")
        print(e.args[0], '\n')

The problem:

Name: A Station:Peroorkada Type:Hospital specialist:Yes specialty:Ophthalmology
Saved name = A, designation = AIMO, mobile = 0, alternate = , email = a@gmail.com, dob = 1999-05-30 00:00:00, specialiast = Yes, specialty = Ophthalmology, institution = ESI Hospital Peroorkada, Trivandrum, bloodgroup = O+, spousename = Dr , children = ddd, present_address = medical college p.o 695011, permanent_address = 

Name: B Station:Ernakulam Type:Hospital specialist:Yes specialty:Anaesthesia
Another uncaught exception occured!
duplicate key value violates unique constraint "app_directorydoctors_name_mobile_email_71312dd8_uniq"
DETAIL:  Key (name, mobile, email)=(B, 1234, a.nb@gmail.com) already exists.

为什么会这样?我怎样才能解决这个问题?

这里提出了一个类似的问题,但显然问题是由于在 update_or_create 中使用了默认参数。我觉得这不适用于我的情况,尽管最终结果是相同的错误

标签: pythondjango

解决方案


推荐阅读