我很难覆盖Django模型上的保存方法来检查多对多字段的限制。使用ManyToManyField覆盖保存Django模型的方法时遇到问题
说我有以下型号:
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
本身。
I.e.我想写:
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.
任何想法的错误是怎么回事错在这里?