簡體   English   中英

在 model 中使用 Django JSONField

[英]Using Django JSONField in model

我正在創建 REST API。

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

我是 Django、python 的新手。 我正在尋找一種在 Django model 中使用 JSON 字段的方法。 我的 model 如下所示 -

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"
      }
    ]
}

我是否應該創建一個新的 model,但創建一個新的 model 會使其添加到我不想要的遷移中。

  1. 如何為上述創建 model?
  2. 如何使用 Django ORM 提供的默認驗證?

我想通了——我們可以為 django 使用 pydantic 或模式。 他們還提供驗證。 我更喜歡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/

Django 現在原生支持JSONField

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM