How can I allow empty fields in my ModelForm while still using unique = True?

此生再无相见时 提交于 2020-01-23 01:04:17

问题


Currently in models.py I have

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

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?


回答1:


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. Change the field to allow NULL, by adding null = True in your model:

    rowname = models.CharField(..., blank = True, null = True, unique = True) 
    
  2. Change empty strings to None in the form:

    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
    


来源:https://stackoverflow.com/questions/10159587/how-can-i-allow-empty-fields-in-my-modelform-while-still-using-unique-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!