gpt4 book ai didi

python - JSON API 标准的 Django Rest Framework 方法

转载 作者:太空宇宙 更新时间:2023-11-03 10:58:32 25 4
gpt4 key购买 nike

我对 Django Rest Framework 很陌生。我在文档中找不到可以让我根据 JSON API 标准 ( jsonapi.org ) 序列化我的模型的内容。

假设我有以下模型。

class Person(models.Model):
name = models.CharField(max_length=200)


class Car(models.Model):
owner = models.ForeignKey(Person)
brand =
model = models.CharField(max_length=200)
plate = models.CharField(max_length=200)

我想以一种能为我提供以下输出的方式对其进行序列化:

{
"data":[
{
"type": "Person",
"id": 1,
"attributes": {
"name": "John",
},
"relationships": {
"cars": [
{
"data": {
"type": "Car",
"id": 1,
"attributes": {
"brand": "Bugatti",
"model": "Veyron",
"plate": "PAD-305",
},
},
},
{
"data": {
"type": "Car",
"id": 2,
"attributes": {
"brand": "Bugatti",
"model": "Chiron",
"plate": "MAD-054",
},
},
},
],
},
},

{
"type": "Person",
"id": 2,
"attributes": {
"name": "Charllot",
},
"relationships": {
"cars": [
{
"data": {
"type": "Car",
"id": 3,
"attributes": {
"brand": "Volkswagen",
"model": "Passat CC",
"plate": "OIJ-210",
},
},
},
{
"data": {
"type": "Car",
"id": 4,
"attributes": {
"brand": "Audi",
"model": "A6",
"plate": "NAD-004",
},
},
},
],
},
}
],

"meta":{
"backend_runtime": "300ms", // processed at the view
}
}

最佳答案

您可以创建您的序列化器以任何您想要的方式返回数据。例如,如果您想忽略确切的模型结构,您可以执行以下操作

from rest_framework import serializers

class PersonSerializer(serializers.Serializer):
"""
Person/Car serializer
"""
id = serializers.IntegerField(read_only=True)
name = serializers.CharField()
attributes = serializers.SerializerMethodField()

def get_attributes(self, obj):
return {"name": obj.name}

如果您想要一个更接近您的模型的序列化器结构,您可以使用以下方法关联模型序列化器:

from rest_framework import serializers

class CarSerializer(serializers.ModelSerializer):
"""Serializes car object"""
class Meta:
model = Car
fields = ('id', 'brand',)


class PersonSerializer(serializers.ModelSerializer):
"""Serializes person and car relationship"""
car = CarSerializer(read_only=True)

class Meta:
model = Person
fields = ('id', 'name', 'car',)

在这两种情况下,您都会将查询集传递给包含这些字段(以及在嵌套模型序列化器中,现有关系)的序列化程序。

关于python - JSON API 标准的 Django Rest Framework 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37150098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com