[Answer]-Django how to access m2m relationship in template

1👍

model_to_dict will only give you a list of private keys (ids) and not all the data of the related objects.

That means you’ll need to create that ‘links’ session variable by iterating through each of the related objects:

request.session['links'] = [model_to_dict(link) for link in my_p.links.all()]

If you want to optimize that, you could use sets, and only add the new profile:

data = model_to_dict(their_p)
if 'links' in request.session:
    request.session['links'].add(data)
else:
    request.session['links'] = set([data])

That should do it, but I think it may not be the best way. I’m not familiarized with PyJade, but I would pass the queryset returned by my_p.links.all() to the template in a context and iterate that instead.

Anyway, I hope that works for you.

Leave a comment