loar
loar

Reputation: 1745

Many to many Field - Accessing attributes

I have these two models related by a ManyToManyField:

class Bar(models.Model):
    name = models.CharField(max_length=25, blank=False)

class Foo(models.Model):

    bar = models.ManyToManyField(Bar, blank=True, related_name='bb')

    def __unicode__(self):
        return '%s' % self.bar.name

In the admin page I get this error:

Exception Type: AttributeError
Exception Value: 'ManyRelatedManager' object has no attribute 'name'

How can I access to the name of bar in Foo? I see the dot notation is not valid.

Upvotes: 4

Views: 2809

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77892

Short answer : you can't.

Long answer : your question "How can I access to the name of bar in Foo" implies a given Foo instance always have one and only one related Bar (not zero, not two, not forty-two, just exactly one), but you're using a ManyToManyField which means a given Foo instance can have zero, one or just any (positive) number of related Bar. In this case, Foo.bar resolves to a queryset, not to a single Bar instance, IOW

f = Foo() 
f.bar.all()

is equivalent to

f = Foo() 
Bar.objects.filter(bb=f) # very weird related name FWIW

Actually in this case Foo.bar would be better named Foo.bars (plural).

If your intent was to have a one to many relationship where each Foo has one single Bar and a Bar has many Foo, you want a ForeignKey instead.

Upvotes: 2

Related Questions