Django unique_together doesn't work with ForeignKey=None

前端 未结 3 1346
抹茶落季
抹茶落季 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 04:14

    The unique together constraint is enforced at the database level, and it appears that your database engine does not apply the constraint for null values.

    In Django 1.2, you can define a clean method for your model to provide custom validation. In your case, you need something that checks for other categories with the same name whenever the parent is None.

    class Category(models.Model):
        ...
        def clean(self):
            """
            Checks that we do not create multiple categories with 
            no parent and the same name.
            """
            from django.core.exceptions import ValidationError
            if self.parent is None and Category.objects.filter(name=self.name, parent=None).exists():
                raise ValidationError("Another Category with name=%s and no parent already exists" % self.name)
    

    If you are editing categories through the Django admin, the clean method will be called automatically. In your own views, you must call category.fullclean().

提交回复
热议问题