Django:如何验证M2M关系? [英] Django: how to validate m2m relationships?

查看:105
本文介绍了Django:如何验证M2M关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个购物篮模型,我想验证的是,该数字不超过 5 可以添加到其中:

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(models.Model):
    items = models.ManyToManyField('Item')

    def save(self, *args, **kwargs):
        self.full_clean()
        super(Basket, self).save(*args, **kwargs)

    def clean(self):
        super(Basket, self).clean()
        if self.items.count() > 5:
            raise ValidationError('This basket can\'t have so many items')

但是当尝试保存 Basket 时,会抛出 RuntimeError ,因为超出了最大递归深度。

But when trying to save a Basket a RuntimeError is thrown because the maximum recursion depth is exceeded.

错误如下:

ValueError: "<Basket: Basket>" needs to have a value for field "basket" before this many-to-many relationship can be used.

如果self.items.count()> 5:行。

It happens in the if self.items.count() > 5: line.

显然,Django的复杂性根本不允许您在保存模型时验证m2m关系。

Apparently Django's intricacies simply won't allow you to validate m2m relationships when saving a model. How can I validate them then?

推荐答案

您可以从不使用干净的方法验证关系。模型。这是因为在清理时间,该模型可能不存在,与您的购物篮一样。某些不存在的东西,也可能没有关系。

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.

您要么需要在表单数据(由@bhattravii指出),或致电 form.save(commit = False)并实现名为 save_m2m ,它实现了限制。

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.

要在模型级别实施限制,您需要收听 m2m_changed 信号。请注意,向最终用户提供反馈要困难得多,但这确实可以防止通过其他方式将篮子装满。

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.

这篇关于Django:如何验证M2M关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆