所以我有以下型号 models.py:
class Coordonnees(models.Model):
latitude = models.CharField(max_length=20)
longitude = models.CharField(max_length=20)
def __str__(self):
return self.latitude+','+self.longitude
class Ecole(models.Model):
nomEcole = models.CharField(max_length=100)
numTel = models.CharField(max_length=100)
coordonnee = models.ForeignKey(Coordonnees, on_delete=models.CASCADE)
def __str__(self):
return self.nomEcole
以及在我的serializers.py中:
class CoordonneesSerializer(serializers.ModelSerializer):
class Meta:
model = Coordonnees
#our fields
fields = ('id','latitude','longitude')
class EcoleSerializer(serializers.ModelSerializer):
class Meta:
model = Ecole
#our fields
fields = ('id','nomEcole','numTel','coordonnee')
问题是当我检查“ Ecole”的json文件时,我得到以下输出
[{"id":1,"nomEcole":"draoui","numTel":"28747484","coordonnee":1}]
所以问题是:我不想显示“ coordonnee”中的1,而是显示纬度和经度
答案 0 :(得分:0)
生成nested representations的最简单方法是使用Meta类中的depth
选项。
class EcoleSerializer(serializers.ModelSerializer):
class Meta:
model = Ecole
depth = 1
fields = ('id', 'nomEcole', 'numTel', 'coordonnee')
输出将类似于:
[
{
"id":1,
"nomEcole":"draoui",
"numTel":"28747484",
"coordonnee": [
{
"id": 1,
"latitude": 0,
"longitude": 0
}
]
}
]
答案 1 :(得分:0)
您正在寻找在Django Rest Framework中序列化nested relationship的方法。为此,您可以将嵌套模型的序列化器用作序列化器字段:
class EcoleSerializer(serializers.ModelSerializer):
coordonnee = CoordonneesSerializer()
class Meta:
model = Ecole
#our fields
fields = ('id', 'nomEcole', 'numTel', 'coordonnee')