実装例その1
from django.core.serializers import serialize
from models import MyModel
def model_to_json_str():
# 1レコードのみ取得
record = MyModel.objects.get(検索条件)
# JSON形式のstrとして出力
# ※record を tuple に入れて渡すこと!!
return serialize('json', (record,))
# [{"model": "myapp.mymodel", "pk": 5, "fields": {"user": "1", "name": "abc", "created_date": "2020-10-21T19:30:38.008"}}]
実装例その2
from json import dumps
from django.forms.models import model_to_dict
from models import MyModel
def model_to_json_str():
# 1レコードのみ取得
record = MyModel.objects.get(検索条件)
my_dict = {
'pk': record.pk,
'fields': model_to_dict(
record,
['user', 'name', 'created_date']
)
}
# JSON形式のstrとして出力
return dumps(my_dict)
# {"pk": 5, "fields": {"user": "1", "name": "abc", "created_date": "2020-10-21T19:30:38.008"}}
参考
model_to_dictの実装
def model_to_dict(instance, fields=None, exclude=None):
"""
Return a dict containing the data in ``instance`` suitable for passing as
a Form's ``initial`` keyword argument.
``fields`` is an optional list of field names. If provided, return only the
named.
``exclude`` is an optional list of field names. If provided, exclude the
named from the returned dict, even if they are listed in the ``fields``
argument.
"""
opts = instance._meta
data = {}
for f in chain(opts.concrete_fields, opts.private_fields, opts.many_to_many):
if not getattr(f, 'editable', False):
continue
if fields is not None and f.name not in fields:
continue
if exclude and f.name in exclude:
continue
data[f.name] = f.value_from_object(instance)
return data