【发布时间】:2020-10-17 03:55:40
【问题描述】:
我正在尝试制作一个 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 文件中,我只获取最后一个产品的数据。
【问题讨论】:
-
你的意思是
{'a':3,'b':5,'c'5}你想得到{'c':5}? -
@AnnZen 不完全是,例如我有两个项目:
{'a' : 3, 'b': 2}和{'c': 1, 'd': 5},我想要一本字典:{'a': 3, 'b': 2, 'c': 1, 'd': 5} -
你只想合并字典,还是也想得到最后一个值?
-
@AnnZen 是的,我想合并字典
标签: python django api django-rest-framework django-views