【问题标题】:save a string as a JSON in Django在 Django 中将字符串保存为 JSON
【发布时间】:2015-09-04 07:35:59
【问题描述】:

我想将 JSON 保存在 Django 字段中,如下所示:

{
    "first_name": "bgbg",
    "last_name": "hbbgh",
    "username": "reza",
    "user_profile": {
        "id": "1ac3ca9c-563e-4f78-b9fa-01552a30585d",
        "gender": "M",
        "birthday": "2015-09-04",
        "country": "Iran",
        "city": "Tehran",
        "street_address": "dsafrfl",
        "state": "dskj",
        "about": "fdgrdshrbfr",
        "social_links": {"linkedin": "http://linkedin.com"},
        "location": "11,22",
        "avatar": "http://127.0.0.1:8000/media/user/1ac3ca9c-563e-4f78-b9fa-01552a30585d/avatar/1ac3ca9c-563e-4f78-b9fa-01552a30585dBooking.gif",
        "verification_code": "9469"
    }

但 social_links 保存如下:

"social_links": "{\"linkedin\": \"http://linkedin.com\"}",

我正在使用 Django REST 框架

class Profile(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    avatar = models.ImageField(blank=True, null=True, upload_to=get_image_path)
    city = models.CharField(max_length=100, blank=True)
    state = models.CharField(max_length=100, blank=True)
    social_links = JSONCharField(max_length=200, blank=True)
...

【问题讨论】:

  • 您确定您不只是在调试器中查看未转义的字符串吗?
  • 我不知道你到底想说什么?
  • 能否保存为文本字段并将响应返回为 return Response(json.loads(social_links), status=status.HTTP_200_OK)
  • 那个字符串是正确的。这里没有问题。
  • @altruistic 如果您使用 JSON 字段,您可以保存不带斜线的字符串。我正在使用jsonfield library 在项目中保存 json 数据。

标签: python json django django-rest-framework


【解决方案1】:

您应该解析您的 json 数据,然后使用 (objects.create) 命令保存。
你也可以使用“Django rest-framework”序列化器。

【讨论】:

    猜你喜欢
    • 2015-11-15
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2017-03-28
    • 2021-09-16
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多