[Answer]-Validate Unique to only have one Property from a certain PropertyCategory


Unfortunately this is a common problem. Even though properties looks like it’s part of a Variant, that ManyToManyField declaration is actually causing the creation of a whole new table that references both Variants and Properties by their primary keys. So when a Variant is created there are, strictly speaking, no Properties associated with it, since that can only happen once the Variant exists in the database. That’s why trying to do the validation by overriding the Model.save() method – a common first approach – can’t work.

Similarly, you can provide custom validation by overriding the Model.clean() method, but at the time this is called (via ModelForm.is_valid(), say) the object and its references haven’t yet been added to the database.

If you’re using Django’s forms (including the admin site), look into ModelForm validation. Basically, you’ll be overriding the clean() method of the ModelForm and validating the form rather than the Model itself.

As for your second question, your idea of adding a BooleanField sounds fine to me. If you’re worried about users inappropriately changing that value then you can control their access to PropertyCategories using permissions in the admin site (or restrict changes with validation). You’re right that changing the value from True to False would present a problem, but that’s a conceptual issue and will be true regardless of the particular method you choose for implementation.

Leave a comment