【问题标题】:How to get data from Django One to Many Fields Model using views into templates如何使用模板中的视图从 Django 一对多字段模型中获取数据
【发布时间】:2021-05-16 09:30:54
【问题描述】:

我想显示 1 个带有关联子项的父字段,并进一步显示子项

我有一个模型

class GrandParent(models.Model):
    name= models.CharField(max_length=50)
    ....

class Parent(models.Model):

    parent = models.ForeignKey(GrandParent, on_delete=models.CASCADE)
    name= models.CharField(max_length=50)
    ....

class Child(models.Models):
    parent = models.ForeignKey(Parent, on_delete=models.CASCADE)
    name= models.CharField(max_length=50)
    ...

我能够从祖父渲染对象,但我无法在模板中链接更多父类对象和子类对象

我在views.py中使用的这种方法

def list(request):
    object_list = GrandParent.published.all()
    ...
    return render('app/list.html')

def detail(request, post,):

    post = get_object_or_404(GrandParent, slug=post,
                        status='published')
                               
    return render(request, 'app/detail.html',
                            {'post' : post,
                            ...
                            
                            })

现在如何在同一详细视图中链接更多类,但使用外键与父类关联。我正在关注 Django 文档,但他们只给出了最多 2 个使用 python shell 的示例,其中只有一个子类我很困惑如何在这个结构中实现。或者任何人已经专门使用这种类型的模型开发了任何项目,所以请分享任何 repo 链接或其他东西,会很棒。

#list.html {% 扩展“_base.html”%}

{% block title %} mysite{% endblock %}
{% block content %}


    <h2>Content </h2>

    
    <ul>
        {% for post in object_list %}
        <a href="{{ post.get_absolute_url }}">
            <li>{{ post.name}}</li></a>
                
        {% endfor %}
    </ul>
{% endblock %}

#detail.html

{% extends "_base.html" %}



{% block title %} freeStreams {% endblock %}
{% block content %}

<div class="card-body">
    <h1 class="card-title">{{ post.title }}</h1>

</div>
    
{% endblock %}

【问题讨论】:

  • 你能补充更多细节吗?你想在哪里显示父类和子类?在模板视图detail.html?你能显示它的代码吗?
  • 当然...我编辑了问题部分。请查看。

标签: python django templates view model


【解决方案1】:

您可以通过 for 循环访问它的所有子视图模板中的一对多。在你的情况下,GrandParent post.parent_set.all()。对于Childparent.child_set.all()。您可以先在终端尝试检查您的数据库和关系是否正确。

将其添加到块内content

detail.html

        {% for parent in post.parent_set.all() %}
                <h1 class="card-title">{{ parent.name }}</h1>
                {% for child in parent.child_set.all() %}
                   <h2 class="card-title">{{ child.name }}</h2>
                    
                {% endfor %}    
        {% endfor %}

【讨论】:

    猜你喜欢
    • 2020-07-07
    • 2016-08-11
    • 2011-10-07
    • 1970-01-01
    • 2019-11-09
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    相关资源
    最近更新 更多