Django unique_together doesn't work with ForeignKey=None

前端 未结 3 1372
抹茶落季
抹茶落季 2021-01-05 03:40

I saw some ppl had this problem before me, but on older versions of Django, and I\'m running on 1.2.1.

I have a model that looks like:

class Category         


        
3条回答
  •  佛祖请我去吃肉
    2021-01-05 03:52

    I had that problem too and solved it by creating a supermodel with clean method (like Alasdair suggested) and use it as base class for all my models:

    class Base_model(models.Model):
      class Meta:
        abstract=True
    
      def clean(self):
        """
        Check for instances with null values in unique_together fields.
        """
        from django.core.exceptions import ValidationError
    
        super(Base_model, self).clean()
    
        for field_tuple in self._meta.unique_together[:]:
            unique_filter = {}
            unique_fields = []
            null_found = False
            for field_name in field_tuple:
                field_value = getattr(self, field_name)
                if getattr(self, field_name) is None:
                    unique_filter['%s__isnull'%field_name] = True
                    null_found = True
                else:
                    unique_filter['%s'%field_name] = field_value
                    unique_fields.append(field_name)
            if null_found:
                unique_queryset = self.__class__.objects.filter(**unique_filter)
                if self.pk:
                    unique_queryset = unique_queryset.exclude(pk=self.pk)
                if unique_queryset.exists():
                    msg = self.unique_error_message(self.__class__, tuple(unique_fields))
                    raise ValidationError(msg)
    

提交回复
热议问题