【问题标题】:How to add another model in ListView that has forign key of the main model如何在具有主模型外键的 ListView 中添加另一个模型
【发布时间】:2021-06-18 03:35:01
【问题描述】:

对不起我的英语不好

我正在制作仪表板网站 我有 2 个模型,第二个模型有第一个模型的外键

json 示例

模型1:

{
   id: 1,
   name: name1,
   location: location1
}

模型2:

{
   id: 1,
   model1_id: 1,
   photo: "http://url/media/pictures/myphoto478998691182.jpg",
   ...
}

所以每个model1实例应该有更多的model2

在我看来,我有一个 model1 的 ListView 我想将 model2 的最后一张照片添加到它的上下文中,引用每个 model1 id

如果我有 2 个 model1 实例,每个都有 5 个 model2 实例,我想按 id 过滤 model2 并获取每个 model1 实例的最后一张照片

Sp 如何修复此代码:

class Model1List(CustomLoginRequired, ListView):
model = Model1
paginate_by = 100

def get_context_data(self, **kwargs):
    photo_list = Model2.objects.filter(model1_id = self.kwargs.get('id'))
    photo = list(photo_list.values_list('photo', flat=True))[-1]
    context = super().get_context_data(**kwargs)
    context['now'] = timezone.now()
    context['photo'] = photo

    return context

为了能够像这样在 html 模板中使用它

{% for object in object_list %}
    <div class="branches-list-unit" id="{{ object.slug }}">
            <h5 class="branch-list-unit__name">{{ object.name }}</h5>
            <img class="branch-list-unit__img" src="{{ object.photo }}" 
   </div>
{% endfor %}

【问题讨论】:

    标签: django django-models django-views django-templates


    【解决方案1】:

    get_context_data 中的上下文名称称为photo。您应该遍历名为 photo 的上下文对象

    您在 html 模板中引用了错误的名称:

    {% for object in photo %}
        <div class="branches-list-unit" id="{{ object.slug }}">
                <h5 class="branch-list-unit__name">{{ object.name }}</h5>
                <img class="branch-list-unit__img" src="{{ object.photo }}" 
       </div>
    {% endfor %}
    

    【讨论】:

    • 但是如何在每次迭代时通过 model1 的 id 过滤 model2 对象? {% for object in object_list %} 第一个对象将有一个 id 我想通过该 id 过滤 model2,然后在过滤后选择最后一张照片
    • 这一行 photo_list = Model2.objects.filter(model1_id = self.kwargs.get('id')) 在 DetailView 中是这样工作的,我该如何在 ListView 中做到这一点?
    • 你的模型是通过外键连接的吗?
    • 是 model2 有 model1 的外键
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 2021-10-11
    • 2018-06-02
    • 1970-01-01
    • 2019-05-25
    • 2021-11-26
    相关资源
    最近更新 更多