How can I ensure that at least one many to many relation is set?
For example: If I have a listing model which has a image field with a many to many relation to images. How can I ensure that at least one image is set
Bonus question: What if the minimum was something other than one? What about a maximum?
You can implement a function to check if the
Listinginstance has at least one image instance, and connect that function to theListingmodel’s pre_save signalIt’ll be something like, (assuming you are using django 1.3)
where you need to implement your_own_exception
The following addition is the response to PO’s further questions
Implementing
Listing.clean()is another way to achieve the same validation rule. Indeed, it’s the semantically correct approach asModel.clean()is meant for custom model validations. But adopting this approach would be less convenient – to trigger theclean()you would have to either manually callfull_clean()(if you don’t use model form), or manually callis_valid()(when using model form), right before callingsave()of a Listing instance. ReferenceOn the other hand, with the
pre_savesignal approach, you can be certain that the validation rule is always applied onListinginstance whenever you callsave()on the instance.It’s not a right-or-wrong to choose one over the other but merely a design decision to make. Both approaches can achieve what you need and keep the business/domain logic (ie. your validation rule) in the Models layer.