代码之家  ›  专栏  ›  技术社区  ›  Kcube

在jinja2中访问字典

  •  0
  • Kcube  · 技术社区  · 1 年前
    {% for blog in data %}
        {% with current_ids=blog.blog_id %}
        {{ like_ids }}
        {{ current_ids }}
        {{ like_ids['bar'] }}
        {% endwith %}
    {% endfor %}
    

    在上面的代码中{{ 点赞_id }}打印{'fo':[],'bar':[<用户: [email protected] >]} {{ 当前ID }}打印foo {{ like_ids['bar'] }}throws error“无法从'like_ids['bar']'中分析余数:'['bar']'”

    我试过了 like_ids.bar 并打印[<用户: [email protected] >] 但是 like_ids.current_ids 不打印任何内容

    尝试设置而不是使用,但问题仍然存在

    def bloglist(request):
    like_ids = {}
    blog_data = Blog.objects.select_related('published_by').filter(status='Published').all()
    for blog in blog_data:
        blog.comment = blog.blogcomment_set.select_related('commented_by').all()
        blog.like = blog.bloglike_set.select_related('liked_by').all()
        like_ids[blog.blog_id] = [like.liked_by for like in blog.like]
    args = {
        'data': blog_data,
        'like_ids': like_ids
    }
    print(args)
    return render(request, 'bloglist.html', args)
    

    这是我的views.py代码

    2 回复  |  直到 1 年前
        1
  •  1
  •   Pycm    1 年前

    更改功能,

    def bloglist(request):
    like_ids = {}
    blog_data = Blog.objects.select_related('published_by').filter(status='Published').all()
    for blog in blog_data:
        blog.comment = blog.blogcomment_set.select_related('commented_by').all()
        blog.like = blog.bloglike_set.select_related('liked_by').all()
        like_ids[blog.blog_id] = [like.liked_by for like in blog.like]
    args = {
        'data': blog_data,
        'like_ids': like_ids
    }
    print(args)
    return render(request, 'bloglist.html', args)
    
    

    到下面。

    def bloglist(request):
        blog_data = Blog.objects.select_related('published_by').filter(status='Published').all()
        args = {
            'data': blog_data,
    
        }
        print(args)
        return render(request, 'bloglist.html', args)
    

    更改模板如下。

    
    {% for blog in data %}
    
      {% for like in blog.bloglike_set.all %}
        {{ like.id }}
      {% endfor %}
    
      {{ blog.id }}
    
    
    {% endfor %}
    
    
    
    

    模板说明。

    {% for blog in data %}
    
    # ALL THE IDs OF LIKES OF CURRENT BLOG
      {% for like in blog.bloglike_set.all %}
        {{ like.id }}
      {% endfor %}
    
    
    # CURRENT BLOG ID
      {{ blog.id }}
    
    
    
    {% endfor %}
    
        2
  •  0
  •   Pycm    1 年前

    你可以访问下面的词典。

    <ul>
    {% for key, value in data.items %} 
      <li>{{key}} - {{value}}</li>
    {% endfor %}
    </ul>
    

    你为什么这么做,

    {% for blog in data %}
        {% with current_ids=blog.blog_id %}
        {{ like_ids }}
        {{ current_ids }}
    

    而你可以做到这一点。

    {% for blog in data %}
        {{ like_ids }}
        {{ blog.blog_id }}