python 无法检索在视图功能中选择的数据

brgchamk  于 2023-04-28  发布在  Python
关注(0)|答案(2)|浏览(133)

`嗨,我无法在视图函数中仅检索media_data。请查看以下数据:

"data": {
    "id": "63f4625a1393d5ff8037a249",
    "group_name": "Favorites",
    "slug": "favorites",
    "parent_id": null,
    "updated_at": null,

    "media_data": {
    "totalAssets": 2,
        "media": [
            {
                "id": "63f849271393d5ff8037a2e5",
                "group_id": "63f4625a1393d5ff8037a249",
                "content_type": "videos",
                "created_at": "2023-02-24T05:20:39.461000"
            },
            {
                "id": "640abd2e1393d5ff8037a3cf",
                "group_id": "63f4625a1393d5ff8037a249",
                "content_type": "videos",
                "created_at": "2023-03-10T05:16:30.210000"
            }
        ]
    }
},
"status": true
}

下面是我的view函数:

def fav_view(request):
    context={}
    context= data    
    context['title'] = 'Favourite data                  
    return render(request, 'admin/favourite_data.html',context)

当我打印数据时,我得到了整个数据,但我只想有media_data。请协助

r7xajy2e

r7xajy2e1#

我认为return render(request, 'admin/favourite_data.html',context)['media_data']应该工作。

nlejzf6q

nlejzf6q2#

假设您有数据dict或响应作为

data = {
    "id": "63f4625a1393d5ff8037a249",
    "group_name": "Favorites",
    "slug": "favorites",
    "parent_id": None,
    "updated_at": None,
    "media_data": {
    "totalAssets": 2,
        "media": [
            {
                "id": "63f849271393d5ff8037a2e5",
                "group_id": "63f4625a1393d5ff8037a249",
                "content_type": "videos",
                "created_at": "2023-02-24T05:20:39.461000"
            },
            {
                "id": "640abd2e1393d5ff8037a3cf",
                "group_id": "63f4625a1393d5ff8037a249",
                "content_type": "videos",
                "created_at": "2023-03-10T05:16:30.210000"
            }
        ]
    }
}

那么你的上下文应该是:

def test(request):
    context = data
    context['title'] = 'Favourite data'
    print(context['media_data'])
    return render(request, 'favourite_data.html', context)

并在html中访问

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{{ media_data }}
</body>
</html>

相关问题