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 %}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…