1、在类中自定义装换
def personToDictionary(person):
if person == None:
return None
dictionary = {}
dictionary["username"] = person.username
dictionary["firstName"] = person.firstName
dictionary["middleName"] = person.middleName
dictionary["lastName"] = person.lastName
dictionary["age"] = person.age
return dictionary
person = Person.objects.get(id = 25)
personDictionary = personToDictionary(person)
2、[使用 Django 的内置序列化程序将 QuerySet
转换为 JSON
]
from django.core import serializers
person = serializers.serialize("json", Person.objects.get(id = 25))
people = serializers.serialize("json", Person.objects.all())
3、使用values()
//全参数返回
person = Person.objects.filter(age = 25).values()
people = Person.objects.all().values()
//返回部分参数
person = Person.objects.filter(age = 25).values("id", "age", "firstName", "lastName")
people = Person.objects.all().values("id", "firstName")