【问题标题】:Trouble overriding save method on Django model with ManyToManyField使用 ManyToManyField 覆盖 Django 模型上的保存方法时遇到问题
【发布时间】:2016-11-11 22:11:13
【问题描述】:

我在覆盖 Django 模型上的 save 方法以检查对多对多字段的限制时遇到问题。

假设我有以下模型:

class Person(models.Model):
    name = models.CharField()

class ClothingItem(models.Model):
    description = models.CharField()
    owner = models.ForeignKey(Person)

class Outfit(models.Model):
    name = models.CharField()
    owner = models.ForeignKey(Person)
    clothing_items = models.ManyToManyField(ClothingItem)

我想对Outfitsave 方法进行限制,以确保给定装备中的每个ClothingItemOutfit 本身具有相同的所有者。

即我想写:

class Outfit(models.Model):
    name = models.CharField()
    owner = models.ForeignKey(Person)
    clothing_items = models.ManyToManyField(ClothingItem)

    def save(self, *args, **kwargs):
        for ci in self.clothing_items:
            if ci.owner != self.owner:
                raise ValueError('You can only put your own items in an outfit!)
        super(Outfit, self).save(*args, **kwargs)

但是当我尝试时,我收到关于 <Outfit: SundayBest>" needs to have a value for field "outfit" before this many-to-many relationship can be used. 的错误

有什么想法吗?

【问题讨论】:

    标签: django django-models django-admin


    【解决方案1】:

    这里有两个问题。直接回答你的问题,错误的基本意思是:如果原始对象(此处为Outfit的实例)未保存在数据库中,则无法引用任何m2m关系。

    听起来您正在尝试在 save() 方法中进行验证,这在 django 中是一种非常糟糕的做法。验证过程通常应在创建Outfit 对象的Form 中进行。要覆盖默认的 django 表单,请参考django ModelAdmin.form。要了解如何对 django 表单进行验证,请查看ModelForm validation

    如果您想参考代码进行 m2m 验证,我找到了 good example from SO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-07
      • 2020-05-11
      • 2020-11-15
      • 2010-10-31
      • 1970-01-01
      相关资源
      最近更新 更多