如何在仍然使用unique = True的同时允许ModelForm中的空白字段? [英] How can I allow empty fields in my ModelForm while still using unique = True?

查看:42
本文介绍了如何在仍然使用unique = True的同时允许ModelForm中的空白字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前在 models.py 中,我有

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

这确实使我们想知道确保两次都没有将相同的值提交给数据库,但是当重复的值是一个空字符串时,有没有一种方法可以使我不产生错误? ? unique 是否接受异常参数?

This does wonders as far as making sure the same value isn't submitted to the database twice but is there a way that I can have unique not raise an error when the value that is a duplicate is an empty string? Does unique take an exception argument?

推荐答案

本质上,您需要请遵循此答案中的建议。尽管Django出于唯一性考虑将''等于'',但它不考虑 NULL 等于 NULL 。因此,您需要存储 NULL 值而不是空字符串。

Essentially, you need to follow the advice in this answer. While Django considers '' equal to '' for purposes of uniqueness, it doesn't consider NULL equal to NULL. So you need to store NULL values instead of empty strings.


  1. 通过在模型中添加 null = True ,将字段更改为允许 NULL

  1. Change the field to allow NULL, by adding null = True in your model:

rowname = models.CharField(..., blank = True, null = True, unique = True) 


  • 将空字符串更改为 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
    


  • 这篇关于如何在仍然使用unique = True的同时允许ModelForm中的空白字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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