【发布时间】: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)
我想对Outfit 的save 方法进行限制,以确保给定装备中的每个ClothingItem 与Outfit 本身具有相同的所有者。
即我想写:
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