我正在创建REST。
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"
}
]
}我应该创建一个新的模型,但是创建一个新的模型会使它添加到我不想要的迁移中。
发布于 2021-05-13 03:43:23
我想-我们可以为django使用pydantic或schema。它们也提供验证。我更喜欢平阳药。
编辑
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)参考化脓性文件,它有我们需要的一切。https://pydantic-docs.helpmanual.io/usage/types/
发布于 2021-10-26 09:12:48
Django现在本机支持JSONField。
https://stackoverflow.com/questions/67469569
复制相似问题