Unique fields that allow nulls in Django

前端 未结 10 1044
闹比i
闹比i 2020-11-28 01:56

I have model Foo which has field bar. The bar field should be unique, but allow nulls in it, meaning I want to allow more than one record if bar field is null,

10条回答
  •  执念已碎
    2020-11-28 02:31

    I recently had the same requirement. Instead of subclassing different fields, I chose to override the save() metod on my model (named 'MyModel' below) as follows:

    def save(self):
            """overriding save method so that we can save Null to database, instead of empty string (project requirement)"""
            # get a list of all model fields (i.e. self._meta.fields)...
            emptystringfields = [ field for field in self._meta.fields \
                    # ...that are of type CharField or Textfield...
                    if ((type(field) == django.db.models.fields.CharField) or (type(field) == django.db.models.fields.TextField)) \
                    # ...and that contain the empty string
                    and (getattr(self, field.name) == "") ]
            # set each of these fields to None (which tells Django to save Null)
            for field in emptystringfields:
                setattr(self, field.name, None)
            # call the super.save() method
            super(MyModel, self).save()    
    

提交回复
热议问题