python - 如何在仍然使用 unique = True 的同时在我的 ModelForm 中允许空字段?

标签 python django django-forms

目前在 models.py 我有

class ModelName(models.Model):
    rowname = models.CharField(max_length=100, blank = True, unique=True) 

就确保相同的值不会两次提交到数据库而言,这确实令人惊奇,但是有没有一种方法可以让我在重复的值是空字符串时不引发错误? unique 是否接受异常参数?

最佳答案

基本上,您需要遵循 this answer 中的建议.虽然 Django 出于唯一性考虑 '' 等于 '',但它并不认为 NULL 等于 NULL。所以你需要存储 NULL 值而不是空字符串。

  1. 通过在您的模型中添加 null = True 来更改字段以允许 NULL:

    rowname = models.CharField(..., blank = True, null = True, unique = True) 
    
  2. 将表单中的空字符串更改为None:

    class ModelNameForm(forms.ModelForm):
        class Meta:
            model = ModelName
        def clean_rowname(self):
            return self.cleaned_data['rowname'] or None
    
    class ModelNameAdmin(admin.ModelAdmin):
        form = ModelNameForm
    

关于python - 如何在仍然使用 unique = True 的同时在我的 ModelForm 中允许空字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10159587/

相关文章:

如果不在配置文件中,Python ConfigParser 使用默认值

Django 获取内联表单管理员中的实例

python - 使用堆有助于提高字符串重新排列的性能

python - opencv错误文件无法打开读取cv::face::FaceRecognizer::read windows

python - 如何设置 urls.py 以与 Django 一起使用 app/urls.py 和 src 中的模板

django - 使用 get_object_or_404 获取数据库值

python - Django 模型问题

python - Django 使用用户配置文件扩展用户(错误 : User has no profile.)

python - 使用三次样条插值时确保一阶微分和二阶微分连续

Python argparse : default argument stored as string, 未列出