Django 模型在添加之前验证 ManyToMany 字段

标签 django django-models

我有一个看起来有点像这样的模型:

class Passenger(models.Model):
    name = models.CharField(max_length=50)
    surname = models.CharField(max_length=50)


class Flight(models.Model):
    capacity = models.IntegerField()
    passengers = models.ManyToManyField(Passenger)

在向航类添加新乘客之前,我想验证乘客数量是否不会超过容量。我想知道什么是最好的方法来解决这个问题。

显然我可以在添加新乘客之前手动检查乘客数量,但也许 django 有一些支持?我尝试编写验证器,但不知道该怎么做。

最佳答案

根据姜戈 docs您可以收听 m2m_changed 信号,将触发 pre_add post_add 行动。

Using add() with a many-to-many relationship, however, will not call any save() methods (the bulk argument doesn’t exist), but rather create the relationships using QuerySet.bulk_create(). If you need to execute some custom logic when a relationship is created, listen to the m2m_changed signal, which will trigger pre_add and post_add actions.

关于Django 模型在添加之前验证 ManyToMany 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50260508/

相关文章:

python - Django,在某个id之前查询对象

python - Django 模板 : Need 2 values to unpack in for loop; got 8

python - 在 Django 中运行测试时出现 NoReverseMatch 错误

python - 如何在单个查询集中组合两个 django 模型对象值

python - django gunicorn sock 文件不是由 wsgi 创建的

django 1.8 测试模型和迁移

python - 如何为 Django 中的所有模型编写 __str__ 方法的通用实现?

python - Django 模型 : default callback: missing "self"

django - 父模型(包括子模型)的序列化

python - Django ajax 格式化约定