我试图找到答案,但不能。在迭代JSONfield的模板中
{% extends "electronic/electronic_base.html" %}
{% load staticfiles %}
{% block content %}
{% for item in micro_all %}
<h1>{{item.title}}</h1>
<table class="table table-condensed">
<tbody>
<tr>
{% for key in item.attributes%}
<td>{{key}}</td>
{% endfor %}
</tr>
</tbody>
</table>
{% endfor %}
{% endblock %}
我可以得到钥匙,但没有价值。试图使用键,值和打印值,但由于某些原因,它给了我单个字母甚至不是表格格式。如何访问模板中的值
from django.db import models
from django.contrib.postgres.fields import JSONField
class Category(models.Model):
title = models.CharField(max_length = 200)
def __str__(self):
return self.title
class SubCategory(models.Model):
title = models.CharField(max_length = 200)
category = models.ForeignKey(Category)
def __str__(self):
return self.title
class Product(models.Model):
title = models.CharField(max_length = 200)
category = models.ForeignKey(Category)
subcategory = models.ForeignKey(SubCategory)
description = models.TextField(blank = True)
attributes = JSONField()
date= models.DateTimeField('дата добавления')
def __str__(self):
return self.title
这是我的models.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Product, Category, SubCategory
def electronic_micro(request):
micro_all = Product.objects.filter(category__title__icontains="Микросхемы")
return render(request,'electronic/micro_all.html', {'micro_all': micro_all})
def electronic_base(request):
return render (request, "electronic/electronic_base.html")
这是我的观点
答案 0 :(得分:7)
您应该能够将其作为普通字典进行迭代:
<table>
{% for key,value in item.attributes.items %}
<tr>
<td>{{key}}</td><td>{{value}}</td>
</tr>
{% endfor %}
</table>