如何使用DRF序列化器将联结表中的数据添加到多个到多个字段?

时间:2018-02-06 10:08:22

标签: django django-rest-framework

我有以下模型,我需要使用DjangoRestFramework序列化器序列化杂志模型:

class Publication(models.Model):
    title = models.CharField(max_length=10)

class MagazinePublication(models.Model):
    publication = models.ForeignKey(Publication, ...)
    magazine = models.ForeignKey(Magazine, ...)

    publication_date = models.DateField(...)

class Magazine(models.Model):
    ...
    publications = models.ManyToManyField(Publication,
                                          through=MagazinePublication)

我想序列化一个像这样的杂志实例,以便出版物包含他们的出版日期从结点(通过)表:

magazine = {
    id: ...,
    publications = [
        {title: ..., publication_date: ...}
        # here title should come from Publication
        # but publication_date from PublicationMagazine (through model)
        # how to do it?
    ]
}

有没有办法用DjangoRestFramework序列化器做到这一点?也欢迎指向文档的链接。

1 个答案:

答案 0 :(得分:1)

首先,您可以在内部Through模型related_name中指定反向关系,如下所示:

class MagazinePublication(models.Model):
   publication = models.ForeignKey(Publication, on_delete=models.CASCADE, related_name='publication_magazines')
   magazine = models.ForeignKey(Magazine, on_delete=models.CASCADE, related_name='magazine_publizations')
   publication_date = models.DateField()

现在您可以在序列化程序中使用此名称。

要实现嵌套序列化,您需要添加MagazinePublicationSerializer:

class MagazinePublicationSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(source='publication.id')
    title = serializers.IntegerField(source='publication.title')
    class Meta:
       model = MagazinePublication

       fields = ('id', 'title', 'publication_date',)

并将其用作MagazineSerializer中的出版物字段:

class MagazineSerializer(serializers.ModelSerializer):
    publications = MagazinePublicationSerializer(source='magazine_publizations', many=True)
    class Meta:
       model = Magazine
       fields = ('id', 'publications',)

查看有关嵌套序列化here的更多详细信息。