【问题标题】:Django save request.POST to JSONField picks last item from list instead of saving the listDjango save request.POST to JSONField 从列表中选择最后一项而不是保存列表
【发布时间】:2022-01-17 02:03:35
【问题描述】:

我有一个从 client.post() 接收 post 请求的视图

        data = {
            "token": create_hash(customer_name),
            "images": [image_1, image_2],
            "name": customer_name,
            "email": "test@email.com",
            "phone": "0612345678",
            "product": "product-sku0",
            "font_family": "Helvetica",
            "font_size": 12,
            "colors_used": (
                "#AAAAAA|White D",
                "#FFFFFF|Black C"
            )
        }

我正在尝试将发布请求作为一个整体保存到 model.JSONfield()。

post 请求键值对如下所示:

'colors_used': ['#AAAAAA|White D', '#FFFFFF|Black C']

当我保存并稍后检索该值时,它看起来像这样:

'colors_used': '#FFFFFF|Black C'

它只保存了最后一个值,而不是将嵌套列表保存在 JSON 字段中。

观点:

@csrf_exempt
def order(request):
    """
    Receives and saves request
    """

    post = request.POST
    files = request.FILES

    print(f"{post=}")

    assert post["token"] == create_hash(post["name"])

    design_obj = RequestDetails.objects.create(
        customer_name = post["name"],
        customer_email = post["email"],
        customer_phone = post["phone"],
        request_json = post
    )

我正在使用 SQLite。

【问题讨论】:

  • 请发表您的看法
  • 我已将视图添加到帖子@Jonas

标签: python json django


【解决方案1】:

原来这只是将查询集转换为 json 字符串时的默认行为。在键级别上,您可以通过 getlist() 获取多值键的所有值。

我最终使用 json.dumps(data) 将整个嵌套数据结构放在单个 json 字符串中,然后将其与请求一起发送。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-08
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多