最基礎的使用方式:
from django.core import serializers data = serializers.serialize("json", SomeModel.objects.all())
可以指定僅序列化某些資料欄位(ex: name & size):
from django.core import serializers data = serializers.serialize('json', SomeModel.objects.all(), fields=('name','size'))
如果我們只要序列化單筆資料,直覺是:
from django.core import serializers data = serializers.serialize("json", SomeModel.objects.get(pk=id))
不過上述是錯的,原來官方文件有這麼一段話:
The arguments to the serialize function are the format to serialize the data to (see Serialization formats) and a QuerySet to serialize. (Actually, the second argument can be any iterator that yields Django objects, but it'll almost always be a QuerySet).
是低~ 所以我們要使用filter()而不是用get():
from django.core import serializers data = serializers.serialize("json", SomeModel.objects.filter(pk=id))