bkev
bkev

Reputation: 1905

Django Newbie ManyRelated Manager not Iterable Question

I'm trying to create a product code (in the admin) by combining elements from two other fields - one of which is a ManyToManyField. I'd like to iterate through that field to find out if a specific product option has been chosen, and append a variation of it to that non-editable product code, like so:

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()

At the moment I'm getting a ManyRelatedManager not Iterable message, so I know I'm doing something wrong, but I don't know what... I apologize in advance for this being a stupid newbie question. Thank you.

Upvotes: 6

Views: 5696

Answers (2)

Antony Hatchkins
Antony Hatchkins

Reputation: 33984

call filter():

def save(self):
    if self.pk!=None:
        if self.shirtclr.filter(shirtcolor='Blue'):
            self.shirtcode = u'%s%s' % ('B', self.shirtmodel)
        else:
            self.shirtcode = self.shirtmodel
    else:
        self.shirtcode = ''

you can avoid self.shirtcode = '' by adding default='' into

shirtcode = models.CharField(_('Code for the shirt'), max_length=80, editable=False, default='')

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798646

Try calling .all() on it.

Upvotes: 14

Related Questions