目前我的代码中有很多python对象,类似于以下内容:
class MyClass():
def __init__(self, name, friends):
self.myName = name
self.myFriends = [str(x) for x in friends]
Run Code Online (Sandbox Code Playgroud)
现在我想把它变成一个Django模型,其中self.myName是一个字符串字段,self.myFriends是一个字符串列表.
from django.db import models
class myDjangoModelClass():
myName = models.CharField(max_length=64)
myFriends = ??? # what goes here?
Run Code Online (Sandbox Code Playgroud)
由于列表是python中常见的数据结构,我希望它有一个Django模型字段.我知道我可以使用ManyToMany或OneToMany关系,但我希望避免代码中的额外间接.
编辑:
我添加了这个相关的问题,人们可能觉得有用.
我在使用带有JSONField的ArrayField插入字段时遇到问题.
models.py
locations = ArrayField(JSONField(null = True,blank = True), blank=True, null = True)
Run Code Online (Sandbox Code Playgroud)
插入
location_arr = [{"locations" : "loc1","amount":Decimal(100.00)},{"locations" : "loc2","amount":Decimal(200.25)}]
instance.locations = location_arr
instance.save()
Run Code Online (Sandbox Code Playgroud)
当我这样做时,我得到了
列"locations"的类型为jsonb [],但表达式的类型为text []
第1行:...... d"= 2517,"locations"= ARRAY ['{"loc ...
提示:您需要重写或转换表达式.
所以我尝试使用以下方式转储它:
import json
location_arr = [{"locations" : "loc1","amount":Decimal(100.00)},{"locations" : "loc2","amount":Decimal(200.25)}]
instance.locations = json.dumps(location_arr)
instance.save()
Run Code Online (Sandbox Code Playgroud)
然后我得到了这个
第1行:...... d"= 2517,"locations"='[{"loc":......
详细信息:"["必须引入显式指定的数组维度.
我在用: