Django: how to validate m2m relationships?

前端 未结 2 2114
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-22 04:18

Let\'s say I have a Basket model and I want to validate that no more than 5 Items can be added to it:

class Basket(mod         


        
2条回答
  •  北海茫月
    2020-12-22 05:00

    You can never validate relationships in the clean method of the model. This is because at clean time, the model may not yet exist, as is the case with your Basket. Something that does not exist, can also not have relationships.

    You either need to do your validation on the form data as pointed out by @bhattravii, or call form.save(commit=False) and implement a method called save_m2m, which implements the limit.

    To enforce the limit at the model level, you need to listen to the m2m_changed signal. Note that providing feedback to the end user is a lot harder, but it does prevent overfilling the basket through different means.

提交回复
热议问题