Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

Django - Get objects from third model using foreignkey

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.

question from:https://stackoverflow.com/questions/65917663/django-get-objects-from-third-model-using-foreignkey

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...