我是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',)
在这两种情况下,您都会将查询集传递给包含这些字段的序列化程序(以及嵌套模型序列化程序中的现有关系).