美文网首页
在 Django 中将 QuerySet 转换为 JSON

在 Django 中将 QuerySet 转换为 JSON

作者: 层林尽染lr | 来源:发表于2022-01-21 11:03 被阅读0次

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")

相关文章

网友评论

      本文标题:在 Django 中将 QuerySet 转换为 JSON

      本文链接:https://www.haomeiwen.com/subject/dldehrtx.html