简体   繁体   English

唯一约束失败的Django模型

[英]UNIQUE constraint failed Django models

I'm working on a Django webapp. 我正在开发Django Webapp。

I'm trying to create a user from signup form. 我正在尝试从注册表单创建用户。

I made sure that there is no user in DB with that username and entered data in signup form and hit enter. 我确保数据库中没有使用该用户名的用户,并以注册形式输入数据,然后按Enter。

There is a default language field that is populated with txt in User user model. 在“用户”用户模型中,存在一个默认语言字段,其中填充了txt

I'm using the following function to populate that field. 我正在使用以下函数填充该字段。

def get_default_language():
    lang=Language.objects.get_or_create(
        name='Plain text',
        lang_code='text',
        slug='text',
        mime='text/plain',
        file_extension='.txt',
    )
    return lang[0].id

But it's giving me the below error 但这给了我下面的错误

IntegrityError at /signup/

UNIQUE constraint failed: djangobin_language.lang_code

Here is the code for Language model 这是语言模型的代码

class Language(models.Model):
    name=models.CharField(max_length=100)
    lang_code=models.CharField(max_length=100, unique=True, verbose_name="Language Code")

Isn't it supposed to get or create the row in Language table? 它不是应该获取或创建语言表中的行吗? Why am I getting this error? 为什么会出现此错误?

Your model is not complete. 您的模型不完整。 You.sre.passing different values for the get_or_create and because it can't find the exact object you are searching for than it tries to create one but the language code it's already used and you get the unique issue. 您为get_or_create传递了不同的值,因为它无法找到您要搜索的确切对象,所以它尝试创建一个对象,但是尝试使用已使用的语言代码,从而遇到了唯一的问题。

I suggest you to use a choices option on your language code field and pass a tuple with the ISO state definitions. 我建议您在语言代码字段上使用选择选项,并通过带有ISO状态定义的元组。

I also suggest you to retrieve based only the language code field and then decide or to update.the object based the other field passed or create a new language object. 我还建议您仅基于语言代码字段进行检索,然后决定或进行更新。该对象基于传递的其他字段或创建新的语言对象。 You must implement your own method to do that 您必须实现自己的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM