Django使用复合主键更新模型

时间:2016-11-18 14:14:48

标签: python django

我正在尝试使用两个主键更新模型。

由于django没有正式支持它,我正在使用解决方法:

class myModel(models.Model):
    class Meta:
        unique_together = (('key1', 'key2'),)

    key1= models.IntegerField(blank=False, primary_key=True)
    key2= models.CharField(blank=False, max_length=30)
    attr3 = models.CharField(max_length=30)
    attr4 = models.CharField(max_length=30)

但是每当我尝试更新现有对象时,我都会收到以下错误:

django.db.utils.IntegrityError: UNIQUE constraint failed: myApp_myModell.key1, myApp_myModel.key2 

我尝试了以下更新我的模型:

myModel.objects.update_or_create(
    key1=kw1, 
    key2= kw2,
    defaults={
    'attr3':attr3_str,
    'attr4':attr4_str,
    })

以及以下内容:

defaults={
    'attr3':attr3_str
    'attr4':attr4_str,
    }
try:
    obj = myModel.objects.get(key1=kw1, key2=kw2)
    for key, value in defaults:
        settatr(obj, key, value)
    obj.save()
except myModel.DoesNotExist:
    print("DOESNT EXISIT")
    new_values = {'key1': kw1, 'key2': kw2}
    new_values.update(defaults)
    obj = myModel(**new_values)
    obj.save()

如何在不出现完整性错误的情况下更新模型的任何想法?

1 个答案:

答案 0 :(得分:1)

我不知道导致真正问题的原因,但删除我模型中的blank=Falseprimary_key=True对我有用:

class myModel(models.Model):
    class Meta:
        unique_together = (('key1', 'key2'),)

    key1= models.IntegerField()
    key2= models.CharField(max_length=30)
    attr3 = models.CharField(max_length=30)
    attr4 = models.CharField(max_length=30)

defaults={
    'attr3':attr3_str
    'attr4':attr4_str,
    }
try:
    obj = myModel.objects.get(key1=kw1, key2=kw2)
    for key, value in defaults:
        setattr(obj, key, value)
    obj.save()
except myModel.DoesNotExist:
    new_values = {'key1': kw1, 'key2': kw2}
    new_values.update(defaults)
    obj = myModel(**new_values)
    obj.save()

感谢您的帮助!