你說的沒錯,這裏的問題是,你的主鍵是name
場。如果數據庫中存在pk
值,Django將執行更新,如果不存在,則會執行插入。例如:
class Cat(models.Model):
name = models.CharField(max_length=255)
cat = Cat(name='Bart')
cat.save() # This creates a new object
print(cat.pk)
> '1'
cat.name = 'Sally'
cat.save() # This updates the object, the pk will still be '1'
print(cat.pk)
> '1'
print(Cat.objects.all())
> [<Cat 'Sally'>]
fluffy = Cat(name='Fluffy')
fluffy.pk = 1
fluffy.save()
'''This will UPDATE the existing object, since an object
with that primary key already exists'''
print(Cat.objects.all())
> [<Cat 'Fluffy'>]
fluffy.pk = 2
fluffy.save()
'''This will CREATE a new object, since no object with
that primary key already exists'''
print(Cat.objects.all())
> [<Cat 'Fluffy'>, <Cat 'Fluffy'>]
如果可能的話,我會建議刪除對name
場primary_key=True
屬性。如果你想name
是唯一的,也許只是設置unique=True
而不是?