【问题标题】:Using Django JSONField in model在模型中使用 Django JSONField
【发布时间】:2021-07-31 19:20:10
【问题描述】:

我正在创建 REST API。

django==3.2.2
djangorestframework==3.12.4
psycopg2==2.8.6

我是 Django 的新手,python。 我正在寻找一种在 Django 模型中使用 JSON 字段的方法。 我的模型如下所示 -

class Question(BaseModel):
.... other code...
    attributes = models.JSONField()

现在我希望属性是 JSON,如下所示

{
    "index": 0,
    "guid": "95161b18-75a8-46bf-bb1f-6d1e16e3d60b",
    "isActive": false,
    "latitude": -25.191983,
    "longitude": -123.930584,
    "tags": [
      "esse",
      "sunt",
      "quis"
    ],
    "friends": [
      {
        "id": 0,
        "name": "Contreras Weeks"
      },
      {
        "id": 1,
        "name": "Dawn Lott"
      }
    ]
}

我是否应该创建一个新模型,但创建一个新模型会使其添加到我不想要的迁移中。

  1. 如何为上述创建模型?
  2. 如何使用Django ORM提供的默认验证呢?

【问题讨论】:

    标签: python django postgresql django-models django-rest-framework


    【解决方案1】:

    我想通了——我们可以为 django 使用 pydantic 或 schema。他们还提供验证。我更喜欢 pydantic。

    1. https://github.com/keleshev/schema
    2. https://pydantic-docs.helpmanual.io/

    编辑

    Pydentic 例子

    架构

    from typing import List
    from pydantic import (
        BaseModel,
        StrictBool,
        StrictInt,
        StrictStr,
    )
    
    class Foo(BaseModel):
    count: int
    size: float = None
    
    
    class Bar(BaseModel):
        apple = 'x'
        banana = 'y'
    
    class AttributesSchema(BaseModel):
        point: StrictInt
        value: StrictStr
        foo: Foo
        bars: List[Bar]
    

    将返回 JSON 格式

    {
        'point': 2,
        'value': 'Any string'
        'foo': {'count': 4, 'size': None},
        'bars': [
            {'apple': 'x1', 'banana': 'y'},
            {'apple': 'x2', 'banana': 'y'},
        ],
    }
    

    验证 - 将此添加到您的序列化程序中

     schema = AttributesSchema
     try:
       errors = schema.validate(data['attributes'])
     except Exception as errors:
       raise serializers.ValidationError(errors)
    

    参考 pydantic 文档,它有我们需要的一切。 https://pydantic-docs.helpmanual.io/usage/types/

    【讨论】:

      【解决方案2】:

      Django 现在原生支持JSONField

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-08-28
        • 2016-11-29
        • 1970-01-01
        • 2016-06-14
        • 1970-01-01
        • 1970-01-01
        • 2020-03-17
        • 2019-07-30
        相关资源
        最近更新 更多