我在Django应用程序中创建了一个模型,并从pgadmin中将数据填充到表中,但是现在当我尝试从应用程序中创建记录时,会引发此完整性错误:
重复的键值违反了唯一约束“ packsapp_foo_pkey”
详细信息:密钥(id)=(4)已经存在。
这是模型。py
class foo(models.Model):
a = models.CharField(max_length=500, default=0)
b = models.EmailField(max_length=500, default=0)
c = models.CharField(max_length=500, default=0)
d = models.CharField(max_length=500, default=0)
我是否总是需要从应用程序本身插入数据?
Views.py
class ProductFormView(CreateView):
model = Product
form_class = Productaddform
template_name = 'packsapp/employee/employeeProductForm.html'
def form_valid (self, form):
product = form.save(commit=False)
print("user ", self.request.user.id)
product.product_owner = Employee.objects.filter(user = self.request.user.id)[0]
product.save()
messages.success(self.request, 'The product was created with success! ')
return redirect('employee:products_table')
答案 0 :(得分:0)
同意主键序列不同步的bruno注释。要解决此问题,请在PG控制台中运行以下命令:
std::aligned_alloc
要在数据库中手动输入值,请确保在插入时为std::size_t n = getNumberOfElements(); // possibly not known at compile time
std::size_t alignment = getRequiredAlignment(); // not known at compile time
makeSureMultiplicationDoesNotOverflow(sizeof(Foo), n); // details irrelevant
void* storage = std::aligned_alloc(sizeof(Foo) * n, alignment); // _aligned_malloc on MSVC
if (!storage) { std::terminate(); }
Foo* buffer = new(storage) Foo[n];
// do stuff with buffer
for(std::size_t i = 0; i < n; ++i) { buffer[i].~Foo(); }
std::free(storage); // _aligned_free on MSVC
调用SELECT setval(pg_get_serial_sequence('packsapp_foo', 'id'), max("id")) FROM "packsapp_foo";
-这将使pk序列保持同步,例如:
nextval(<sequence>)
这同样适用于您在表列上可能具有的任何其他序列。有关更新序列,请参见Postgres Docs