我使用下面定义的模型获得完整性,当我进行更改并再次从django管理员保存数据时会发生这种情况。 该错误由obj.save()触发。 错误如下:
Exception Type: IntegrityError at /admin/users/data/1/change/
Exception Value: UNIQUE constraint failed: users_data.id
我该怎么做。
class Data(models.Model):
author = models.ForeignKey(User, null=True, editable=False, on_delete=models.CASCADE)
address = models.CharField(max_length=300,blank=True,null=True,help_text=("enter the address"))
contact = models.IntegerField(blank=True,null=True,help_text=("enter the contact"))
username = models.CharField(max_length=100,blank=True,null=True,help_text=("enter the username"))
password = models.CharField(max_length=100,blank=True,null=True,help_text=("enter the strong password"))
creation_date = models.DateTimeField(editable=False,null=True)
last_modified = models.DateTimeField(editable=False,null=True)
def save(self,*args, **kwargs):
if not self.creation_date:
self.creation_date = timezone.now()
self.last_modified = timezone.now()
return super(Data, self).save(self,*args, **kwargs)
def __str__(self):
return (self.username)
@receiver(post_save,sender=Data)
def datasaver(sender, instance, **kwargs):
address = instance.address
contact = instance.contact
username = instance.username
user_password = instance.password
class CustomAdmin(admin.ModelAdmin):
search_fields = ('first_name', 'email', 'username', )
def save_model(self, request, obj, form, change):
obj.author = request.user
obj.password = ''
obj.save()
def get_queryset(self, request):
qs = super(CustomAdmin, self).get_queryset(request)
if request.user.is_superuser:
return qs
return qs.filter(author=request.user)
答案 0 :(得分:0)
不要这样做。 Django提供了一种更好的方法来保存修改日期和创建日期。请改用此方法,并删除覆盖的保存方法并发布保存信号。
替换
creation_date = models.DateTimeField(editable=False,null=True)
last_modified = models.DateTimeField(editable=False,null=True)
使用
creation_date = models.DateTimeField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)