1.使用
2.使用
如何获得text/value
之类的新格式的JSON:
[
{
"name": "doc2",
"directions": [
"mar",
"qwe"
]
},
{
"name": "John",
"directions": [
"Surgery",
"qwe"
]
}
]
而不是:
[
{
"name": "doc2",
"directions": [
{
"name": "mar"
},
{
"name": "qwe"
}
]
},
{
"name": "John",
"directions": [
{
"name": "Surgery"
},
{
"name": "qwe"
}
]
}
]
以下是我的models.py
和serializers.py
模块:型号.py
class Directions(models.Model):
name = models.CharField(max_length=355)
def __str__(self):
return self.name
class Doctors(models.Model):
name = models.CharField(max_length=255)
directions = models.ManyToManyField(Directions)
def __str__(self):
return self.name
序列化程序.py
class DirectionsSerializer(serializers.ModelSerializer):
class Meta:
model = Directions
fields = ('name',)
class DoctorsSerializer(serializers.ModelSerializer):
directions = DirectionsSerializer(many=True)
class Meta:
model = Doctors
fields = ('name', 'directions')
实现此目的有两种选择:
1.使用Custom relational fields
[drf docs]
对于您的情况,我们可以定义一个关系字段,使用它的顺序、标题和持续时间将音轨序列化为自定义字符串表示:
class DirectionsSerializer(serializers.RelatedField):
def to_representation(self, value):
return value.name
class DoctorsSerializer(serializers.ModelSerializer):
directions = DirectionsSerializer(many=True)
class Meta:
model = Doctors
fields = ['name', 'directions']
然后,这个自定义字段将序列化为以下表示形式:
[
{
"name": "doc2",
"directions": [
"mar",
"qwe"
]
},
{
"name": "John",
"directions": [
"Surgery",
"qwe"
]
}
]
2.使用StringRelatedField()
[drf docs]
CCD_ 6可以用于使用其CCD_ 7方法来表示关系的目标。
对于您的案例,以下序列化程序:
class DoctorsSerializer(serializers.ModelSerializer):
directions = serializers.StringRelatedField(many=True)
class Meta:
model = Doctors
fields = ['name', 'directions']
将序列化为以下表示形式:
[
{
"name": "doc2",
"directions": [
"mar",
"qwe"
]
},
{
"name": "John",
"directions": [
"Surgery",
"qwe"
]
}
]
此字段为read_only
。
自变量:
many
-如果应用于多对多关系,则应将此参数设置为True