Search code examples
pythondjangotemplatesmany-to-many

ManytoMany field django template when models are in different apps


My question is similar to this. I have 2 models linked with m2m field and I want to render the field in template. How can I do this when my 2 models are in different apps:

apps/qapp/models

class Area(models.Model):
    name = models.CharField(max_length=100, primary_key=True)
    def __unicode__(self):
        return self.name

apps/worksheets/models

class Place(models.Model):
    id = models.IntegerField(primary_key=True) 
    name = models.CharField(max_length=100, primary_key=True)
    area = models.ManyToManyField('qapp.Area',related_name='area')

Solution

  • There are 2 ways we can show m2m fields data in template.

    1. If you want to show all the places related to an area; see @Vitor's answer.

    2. If you want to show all the areas related to a single place; see below -

    queryset for the places place1 = Place.objects.filter(id=1)

    Now in the template:

    {% for place2 in place1 %}
    
        {% for area1 in place2.area.all %}
    
            <p>{{area1.name}}</p>
    
        {% endfor %}
    
    {% endfor %}
    

    I have deliberately taken variables like above so that someone new can understand where to put which variable.