0

I have Models.

class M1(models.Model):
   ....

class M2(models.Model):
   ....

class M3(models.Model):
   n1 = models.ForeignKey(
        M1, related_name="M1_related", on_delete=models.CASCADE
    )
  n2 = models.ForeignKey(
        M2, related_name="M2_related", on_delete=models.CASCADE
    )

In templates I have M1 object. Using it, I want to get all M2 objects related to M1 object.

I tried {{M1_object.M1_related.n2.all}} but is blank. Doing {{M1_object.M1_related}} gives me M3.None

I looked at these two questions 1 and 2. They are similar to mine but not helpful.

Newbie
  • 343
  • 2
  • 13

2 Answers2

0

As Pierre mentioned template tags achieve this.

Firstly create the file structure. Go into the app directory where the tag is needed, and add these files:

templatetags
templatetags/__init__.py
templatetags/custom_query_tags.py

The templatetags/custom_query_tags.py file:

from django import template

register = template.Library()

@register.simple_tag
def get_m2_objects(M1_object_id):
    m3s = M3.objects.filter(n1__id=M1_object_id)
    new_list = []
    for each_m3 in m3s:
        new_list.append(each_m3.n2)
    return new_list

In the template:

{% load custom_query_tags %} <!--don't forget to load the custom_query_tags.py file in the template. -->


{% get_m2_objects M1_object.id as all_related_m2s %}

{% for each_m2_object in all_related_m2s %}
    <!-- Your code here -->
{% endfor %}
Siva Sankar
  • 1,672
  • 1
  • 9
  • 16
-1

Maybe you can add a ManyToManyField with an intermediate model :

class M2(models.Model):
   m1_objects = models.ManyToManyField(M1, through='M3', related_name='m2_objects')

Then you can do :

{{ M1_object.m2_objects.all }}
Benbb96
  • 1,973
  • 1
  • 12
  • 21