【发布时间】:2020-09-03 10:47:24
【问题描述】:
出现错误-我将一个表单从 html 保存到我的数据库中 当我尝试保存下一个时,它给了我这个错误- 客户的IntegrityError (1062,“重复条目 'ad138e46-edc0-11va-b065-a41g7252ecb4'' 键'customer.PRIMARY'”) 请解释我在 models.py 中的 uuid 是 -
class customer(models.Model):
customerid = models.CharField(default=str(uuid.uuid4()), max_length=500, primary_key=True)
customername=models.CharField(max_length=100)
请帮忙
更新
Form.py
class createcustomerform(ModelForm):
class Meta:
model=customer
fields=[
'customername']
更新了 Models.py
import uuid
from uuid import UUID
from django.contrib.auth.models import User
from django.dispatch.dispatcher import receiver
from django.utils.translation import ugettext_lazy as _
from django.db.models.signals import pre_save
class customer(UUIDMixin,models.Model):
customername=models.CharField(max_length=100)
def __str__(self):
return self.customername
class UUIDMixin(models.Model):
uuid = models.UUIDField(blank=True,db_index=True,default=None,help_text=_('Unique identifier'),max_length=255,null=True,unique=True,verbose_name=_('UUID'))
class Meta:
abstract = True
@classmethod
def check_uuid_exists(cls, _uuid):
#Determine whether UUID exists """
manager = getattr(cls, '_default_manager')
return manager.filter(uuid=_uuid).exists()
@classmethod
def get_available_uuid(cls):
#Return an Available UUID """
row_uuid = uuid.uuid4()
while cls.check_uuid_exists(uuid=row_uuid):
row_uuid = uuid.uuid4()
return row_uuid
@receiver(pre_save)
def uuid_mixin_pre_save(sender, instance, **kwargs):
if issubclass(sender, UUIDMixin):
if not instance.uuid:
manager = getattr(instance.__class__, '_default_manager')
use_uuid = uuid.uuid4()
while manager.filter(uuid=use_uuid):
use_uuid = uuid.uuid4()
instance.uuid = use_uuid
#Automatically populate the uuid field of UUIDMixin models if not already populated.
【问题讨论】:
-
为什么不使用
models.UUIDField? -
没错,使用
models.UUIDField,同时添加您的表单代码:)
标签: django django-models django-forms uuid