我有以下MySQL表:
- 制作
-model
-Styles
models.py(自动生成)
class Makes(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=13)
nicename = models.CharField(db_column='niceName', max_length=13)
class Meta:
managed = False
db_table = 'Makes'
class Models(models.Model):
id = models.CharField(primary_key=True, max_length=36)
name = models.CharField(max_length=23)
nicename = models.CharField(db_column='niceName', max_length=23)
make = models.ForeignKey(Makes, models.DO_NOTHING)
class Meta:
managed = False
db_table = 'Models'
serializers.py
class MakeSerializer(serializers.ModelSerializer):
class Meta:
model = Makes
fields = ('name',)
class ModelSerializer(serializers.ModelSerializer):
make = MakeSerializer(many=True, read_only=True)
class Meta:
model = Models
fields = ('make','id', 'name', 'nicename')
views.py
class MakesList(generics.ListCreateAPIView):
queryset = Makes.objects.all()
serializer_class = MakeSerializer
class MakesDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = Makes.objects.all()
serializer_class = MakeSerializer
换句话说,Styles是父表,它包含连接两者的Make和Model的ID。
如何与DRF建立关系以获得预期的输出:
"makes": [{
"id": 1,
"name": "Acura",
"models": [{
"id": "Acura_ILX",
"name": "ILX",
"styles": [{
"id": "1"
"name": "Sport"
}]
}, {
"id": "Acura_ILX_Hybrid",
"name": "ILX Hybrid",
"styles": [{
"id": "1"
"name": "Sport"
}]
}, {
"id": "Acura_MDX",
"name": "MDX",
"styles": [{
"id": "1"
"name": "Sport"
}]
}]
答案 0 :(得分:2)
所以基本上你要做的就是创建一堆序列化器。
class MakeSerializer(serializers.ModelSerializer):
class Meta:
model = Make
fields = ('your', 'fields', 'here')
class ModelSerializer(serializers.ModelSerializer):
make = MakeSerializer(many=True, read_only=True)
class Meta:
model = Model
fields = ('name', 'just_fields_here')
class StyleSerializer(serializers.ModelSerializer):
model = ModelSerializer(many=True, read_only=True)
class Meta:
model = Style
fields = ('your_fields_here_again', )
这就是你的序列化程序的简单方式。
这就是你如何使用它:
>>> make = Make.objects.create(name="Audi")
>>> model1 = Model.objects.create(make=make, name='R8')
>>> model2 = Model.objects.create(make=make, name='Q7')
>>> Style.objects.create(model=model1, name='Sport')
>>> Style.objects.create(model=model2, name='SUV')
>>> serializer = MakeSerializer(instance=make)
并使用
>>> serializer.data
输出应该如下:
{
'name': 'Audi',
'model': [{
'name': 'R8',
'style': {
'name': 'Sport'
}
},{
'name': 'Q7',
'style': {
'name': 'SUV'
}
}]
}