2016-11-11 80 views
1

我很难覆盖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) 

我想提出一个限制上的Outfitsave方法以确保在一个给定的衣服每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.

任何想法的错误是怎么回事错在这里?

回答

2

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

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

如果您想要参考m2m验证的代码,我找到了一个good example from SO