gpt4 book ai didi

python - 我怎样才能在我的模板中获取 JSONfield 的值

转载 作者:太空宇宙 更新时间:2023-11-03 13:13:12 25 4
gpt4 key购买 nike

我试图找到答案,但找不到。当我遍历 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

这是我的模型.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")

这是我的看法

最佳答案

您应该能够将其作为普通字典进行迭代:

<table>
{% for key,value in item.attributes.items %}
<tr>
<td>{{key}}</td><td>{{value}}</td>
</tr>
{% endfor %}
</table>

关于python - 我怎样才能在我的模板中获取 JSONfield 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38168856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com