我正在尝试制作 Django Rest API 。有了这个API,我想发送一个产品列表。为此,我尝试建立一个for循环来升级包含我的数据的字典。
这是我的代码:
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import product, by_product
#List all the products
@api_view(['GET'])
def listing(request):
context = {}
product = product.objects.filter(dispo=1).order_by('name')
for product in product:
if not product.price_kg:
price = product.price_uni
unit = 'units'
else:
price = product.price_kg
unit = 'Kg'
dictionary = {
'id' : product.id,
'name': product.name,
'price': price,
'unit': unit,
'category': product.categorie,
'byProduct': [],
}
context = ({**context, **dictionary}) #Upgrade my dictionary
by_products = by_product.objects.filter(product_id=product.id).order_by('bycat')
for byprod in by_products:
context['byProduct'].append({
'id' : byprod.id,
'name' : byprod.bycat,
})
if product.redu:
context['oldPrice'] = product.redu
return Response(context)
在我的JSON文件中,我只获取最后一个产品的数据。
答案 0 :(得分:1)
以下是升级词典的方法:
bot.login(token);
根据评论,这基本上是希望合并字典:
context.update(dictionary)
输出:
lst = [{'a':1, 'b':2}, {'c':3, 'd':4}, {'e':5, 'f':6}]
dct = {k:v for d in lst for k,v in d.items()}
print(dct)
答案 1 :(得分:0)
据我了解,您希望以这种格式输出
例如{dict 1},{dict 2} ......... {dict n},而您想在id, name
键和{{1 }}。 (这就是我从您的问题中得出的假设)。可能您可以执行以下操作:
byProduct