我正在尝试通过组合其他两个字段的元素(其中之一是 ManyToManyField)来创建产品代码(在管理员中)。我想遍历该字段以查明是否已选择特定产品选项,并将其变体附加到不可编辑的产品代码中,如下所示:
class ShirtColorClass(models.Model):
shirtcolor = models.CharField(_('Shirt Color'), unique=True, max_length=40)
def __unicode__(self):
return self.shirtcolor
class ShirtClass(models.Model):
shirtmodel = models.CharField(_('Model of Shirt'), max_length=40)
shirtclr = models.ManyToManyField(_(ShirtColorClass, verbose_name='Shirt Color'))
shirtcode = models.CharField(_('Code for the shirt'), max_length=80, editable=False)
#...10 more fields...
def __unicode__(self):
return self.shirtmodel
def save(self):
for item in self.shirtclr: #these are the lines I'm not sure how to do
if 'Blue' in self.shirtclr:
self.shirtcode = u'%s%s' % ('B', self.shirtmodel)
else:
self.shirtcode = self.shirtmodel
super(ShirtClass,self).save()
目前我收到了 ManyRelatedManager not Iterable 消息,所以我知道我做错了什么,但我不知道是什么......我提前为这是一个愚蠢的新手问题道歉。谢谢。
最佳答案
尝试对其调用.all()
。
关于Django 新手 ManyRelated Manager 不可迭代的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2059529/