Django:v2.1.5 DRF:v3.9.1 mariaDB:v10.3
嗨,我是DRF新手,我一直在努力解决json字段。
DRF不支持与mariaDB一起使用的官方json字段类型,即使存在用于mysql(django-mysql)的第三方软件包,但与mariaDB不兼容。
所以我搜索并开始实现自定义jsonfield,它看起来像:
model.py:
function Insert(){
tinymce.activeEditor.execCommand('mceInsertContent', false, '<span class="bgTest" data-prefix="ABC">This is a inserted text</span> ');
}
document.querySelector(".tinymce").addEventListener("keydown", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
Insert();
}
});
serializers.py:
class JSONField(models.TextField):
def to_dict(self, value):
""" convert json string to python dictionary """
return json.loads(value)
def to_json(self, value):
""" convert python dictionary to json string """
return json.dumps(value)
def from_db_value(self, value, expression, connection):
""" convert string from db to python dictionary """
if value is None:
return value
return self.to_dict(value)
def to_python(self, value):
""" convert model input value to python dictionary """
if isinstance(value, dict):
return value
if value is None:
return value
return self.to_dict(value)
def get_prep_value(self, value):
""" convert python dictionary to string before writing to db """
return self.to_json(value)
class Project(models.Model):
objects = models.Manager()
project_user = JSONField(null=True)....
views.py:
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = ('project_code'...)
def create(self, validated_data):
"""
Create and return a new `Project` instance, given the validated data.
"""
return Project.objects.create(**validated_data)
请让我知道我在这里做错了什么,或者是使用3rd party包而不是自定义jsonfield的方法
非常感谢,祝大家有美好的一天!
答案 0 :(得分:0)
对于遭受此类问题困扰的人们,我实际上以非正式的方式解决了该问题。我在数据库中将JSONfield设置为文本字段,并在视图中处理(str-> json),(json-> str)。但是,这又是一种非正式的方式(我认为),您将需要除此以外的另一种解决方案。如果找到一个,请给我和其他人分享:)