自定义JsonField,用json.dumps转成字串存到db里,从db取出来用json.loads转会真实类型
可以存dict或者list,默认不传的时候存空字串,注意这个字段只能用来存取,不要用来做filter
import json
from django.db import models
class CustomJsonField(models.TextField):
def get_db_prep_value(self, value, connection, prepared=False):
"""存到db"""
if not value:
return super().get_db_prep_value('', connection, prepared)
return json.dumps(value, ensure_ascii=False)
def from_db_value(self, value, expression, connection):
"""从db取出"""
if not value:
return ''
return json.loads(value)
class Person(models.Model):
name = models.CharField('名字', max_length=255)
desc = CustomJsonField('说明', default='')
# 创建和调用举例
Person.objects.create(name='zhangsan', desc=[1,2,3])
>>> <Person: Person object (1)>
Person.objects.create(name='lisi', desc={'x':1, 'y':2})
>>> <Person: Person object (2)>
Person.objects.get(id=1).desc
>>> [1, 2, 3]
Person.objects.get(id=2).desc
>>> {'x': 1, 'y': 2}