Django在单个视图中序列化多个模型

时间:2018-04-02 23:05:53

标签: django serialization model

这是场景,我有两个模型Offre和Recruteur

class Recruteur(models.Model):  
    [...]
    entrepriseName = models.CharField(max_length=50)
    [...]

class Offre(models.Model):          
    [...]
    idRecruteur = models.ForeignKey(Recruteur,verbose_name = "idRecruteur", on_delete=models.CASCADE, default=None)
    [...]   

我有以下序列化器:

class RecruteurByIdSerializer(serializers.ModelSerializer):

    class Meta:
        model = Recruteur
        fields = ( 'entrepriseName',)

class OffreSerializer(serializers.ModelSerializer):
    recruteur = RecruteurByIdSerializer(many=True, read_only=True)
    class Meta:

        model = Offre
        fields = ( 'title', 'dateAjout', 'description', 'recruteur')

我期待这个结果:

enter image description here

但是我得到了这个:

enter image description here

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您必须提供source参数,如下所示,

class OffreSerializer(serializers.ModelSerializer):
    entrepriseName = RecruteurByIdSerializer(source='idRecruteur', read_only=True)

    class Meta:
        model = Offre
        fields = ('title', 'dateAjout', 'description', 'entrepriseName')