Django:模板通过表从多到多显示值

时间:2018-10-25 14:14:01

标签: python django django-templates many-to-many relationship

我有3个模型,我正尝试访问并显示多对多关系(Django)中“通过”表中的数据。

我尝试显示3件事:

  • 艺术品图像,
  • 使用的翻译语言
  • 艺术品的翻译名称

我正在做最后一个。它来自多对多关系的“直通”链接);有什么主意吗?

Models.py:

class Language(models.Model):
    LANG = (
        ('FR', 'FR'),
        ('EN', 'EN'),
    )
    lang_selected = models.CharField(max_length=3, choices=LANG, verbose_name='Availlable language')

    def __str__(self):
        return self.lang_selected 

class Artwork(models.Model):
    artwork_image = models.CharField(max_length=100, null=True, verbose_name="Artwork image")
    version = models.ManyToManyField(Language, through='Artwork_language', verbose_name="link artwork -> language")

    def __str__(self):
        return self.artwork_image

class Artwork_language(models.Model):
    Artwork = models.ForeignKey(Artwork, on_delete=models.CASCADE)
    Language = models.ForeignKey(Language, on_delete=models.CASCADE)

    artwork_name = models.CharField(max_length=100, null=True, verbose_name="Artwork name")

    def __str__(self):
        return str(self.Artwork) + " translated to " + str(self.Language)

views.py

class Accueil(TemplateView):
    template_name = 'isa/accueil.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        context['artwork'] = Artwork.objects.all()
        context['language'] = Language.objects.all()
        context['artwork_language'] = Artwork_language.objects.all()

        return context

模板(accueil.html)

    <h1>Image  | Language translation | Translated name</h1>

{% for artwork in artwork %}
    Image : {{ artwork.artwork_image }} <br/>
        {% for lang in artwork.version.all %}
                Language translation :  {{ lang }}  <br/>
                Translated name :  {{ ### }}
                {% for i in lang.artwork_language %}
                {{ i.artwork_name }}
                {% endfor %}
                <br/>
        {% endfor %}

preview

我在Translated name : {{ ### }}中做了很多尝试,但是似乎没有任何效果;我完全在错误的道路上吗?

2 个答案:

答案 0 :(得分:1)

正如我在评论中所说,您应该遵循与Artwork_language的关系,然后从FK转向“语言”:

{% for artwork_lang in artwork.artwork_language_set.all %}
    Language translation :  {{ artwork_lang.Language }}  <br/>
    Translated name :  {{ artwork_lang.artwork_name }}
{% endfor %}

答案 1 :(得分:0)

当您访问相关实例(多对多字段的相关管理器)时,无法引用贯通模型的属性。您可以在直通模型中使用fk的默认range("m2").characters

related_name