how to get at the manytomany fields in for

142 views
Skip to first unread message

MikeKJ

unread,
Nov 22, 2013, 5:53:42 AM11/22/13
to django...@googlegroups.com
Got this model
class AdviceLevel(models.Model):
    advice = models.ForeignKey(Advice)
    organisation = models.ForeignKey(Organisation)
    specialism = models.ManyToManyField(Specialism, null=True, blank=True)
    service_restriction = models.TextField(null=True, blank=True)

in the view
    dir_list = AdviceLevel.objects.all().filter(advice=advice)

so I get a list

in the template
    {% for d in dir_list %}
        {{ d.organisation.title }}
        {{ d.servicerestriction }}    //etc
 
// but when it comes to the many to many how do I access each
// d.specialsm gets however many selected <django.db.models.fields.related.ManyRelatedManager object at 0x973bb6c>
// tried d.specialism_set.all but I get AttributeError: 'ManyRelatedManager' object has no attribute 'set' also
// tried for x in d.specialism but get  'AdviceLevel' object has no attribute 'specialsm'

So how do I access the individual fields of the manytomany results of specialism in the template please?

Daniel Roseman

unread,
Nov 22, 2013, 8:40:31 AM11/22/13
to django...@googlegroups.com
The are many objects, so you need to iterate over them:

    {% for spec in d.specialism.all %}
        {{ spec.field1 }} etc
    {% endfor %}
--
DR. 

Arun K Reddy

unread,
Nov 22, 2013, 8:30:24 PM11/22/13
to django...@googlegroups.com
Small correction to what Daniel suggested:
    {% for spec in d.specialism_set.all %}
        {{ spec.field1 }} etc
    {% endfor %}

Daniel Roseman

unread,
Nov 24, 2013, 1:48:25 PM11/24/13
to django...@googlegroups.com
No, that is incorrect. `dir_list` is a queryset of AdviceLevel objects, and `specialism` is a field defined directly on that model. You only need to add `_set` for a reverse relationship, which this isn't.
--
DR.
Reply all
Reply to author
Forward
0 new messages