主键和django中的唯一键 [英] Primary key and unique key in django

查看:399
本文介绍了主键和django中的唯一键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义主键,需要在模型中的特定数据上设置。

I had a custom primary key that need to be set up on a particular data in a model.

这还不够,因为尝试插入重复的号码成功。所以现在当我将 primary_key = True 替换为 unique = True 它可以正常工作并拒绝重复的数字!但是根据文档使用字段)。

This was not enough, as an attempt to insert a duplicate number succeeded. So now when i replace primary_key=True to unique=True it works properly and rejects duplicate numbers!!. But according this document (which uses fields).

primary_key = True 隐含 null = False
unique = True。


这让我困惑,为什么
它接受第一个地方
的价值,具有内置的 unique = True

谢谢。

更新声明

   personName = models.CharField(primary_key=True,max_length=20)


推荐答案

使用 AutoField primary_key 代替。

编辑

如果您不使用 AutoField 必须手动计算/设置主键字段的值。这很麻烦有没有理由您需要 ReportNumber 到主键?您仍然可以拥有唯一的报告号码,您可以在其上查询报告以及自动递增整数主键。

If you don't use an AutoField, you'll have to manually calculate/set the value for the primary key field. This is rather cumbersome. Is there a reason you need ReportNumber to the primary key? You could still have a unique report number on which you can query for reports, as well as an auto-incrementing integer primary key.

编辑2: strong>

Edit 2:

当您说允许重复主键值时,您会指出现在发生的是具有相同主键的现有记录已更新 - 没有实际上两个对象在数据库中具有相同的主键(不可能发生)。问题是Django的ORM层选择执行 UPDATE (修改现有DB记录)与 INSERT INTO (创建一个新的DB记录)。从 django.db.models.base.Model.save_base()中查看此行:

When you say duplicate primary key values are allowed, you indicate that what's happening is that an existing record with the same primary key is updated -- there aren't actually two objects with the same primary key in the database (which can't happen). The issue is in the way Django's ORM layer chooses to do an UPDATE (modify an existing DB record) vs. an INSERT INTO (create a new DB record). Check out this line from django.db.models.base.Model.save_base():

if (force_update or (not force_insert and
        manager.using(using).filter(pk=pk_val).exists())):
    # It does already exist, so do an UPDATE.

特别是这段代码:

manager.using(using).filter(pk=pk_val).exists()

这说:如果数据库中存在与 Model 相同的主键的记录,然后执行更新。因此,如果您重新使用主键,Django会假定您正在进行更新,因此不会引发异常或错误。

This says: "If a record with the same primary key as this Model exists in the database, then do an update." So if you re-use a primary key, Django assumes you are doing an update, and thus doesn't raise an exception or error.

我认为最好的想法是让Django为你生成一个主键,然后有一个单独的字段( CharField 或者其他) c $ c> unique 约束。

I think the best idea is to let Django generate a primary key for you, and then have a separate field (CharField or whatever) that has the unique constraint.

这篇关于主键和django中的唯一键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆