Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 381
loar Avatar asked Oct 21 '25 03:10

loar


1 Answers

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.

like image 111
bruno desthuilliers Avatar answered Oct 23 '25 16:10

bruno desthuilliers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!