【问题标题】:Add a dictionary into another one with a loop in Django [closed]在Django中使用循环将字典添加到另一个字典中[关闭]
【发布时间】: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


【解决方案1】:

据我了解,您希望以这种格式输出

例如 { dict 1} , {dict 2} ......... {dict n} 而您想在 byProduct 键和 oldPrice 中添加诸如 id, name 之类的字段。 (这就是我从你的问题中假设的)。也许你可以做这样的事情:

@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': [],
        }   
        by_products = by_product.objects.filter(product_id=product.id).order_by('bycat')
        
        for byprod in by_products:
            dictionary['byProduct'].append({
            'id' : byprod.id,
            'name' : byprod.bycat,
            })
        if product.redu:
            dictionary['oldPrice'] = product.redu
        context.append(dictionary) #Upgrade my dictionary
    return Response(context)

【讨论】:

  • 我尝试按照您的建议进行操作,但出现此错误:列表索引必须是整数或切片,而不是 str
  • 您可以将所做的更改粘贴到 pastebin 链接上吗? pastebin.com 然后将链接粘贴到此处。
  • 你到底想要什么?整个文件还是只是视图?
  • 终于成功了,谢谢!!
【解决方案2】:

以下是升级词典的方法:

context.update(dictionary)

根据cmets,这基本上是想合并字典:

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)

输出:

{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6}

【讨论】:

    猜你喜欢
    • 2018-07-27
    • 2022-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-23
    • 2022-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多