Django Rest Framework:从另一个模型获取序列化程序中的相关特定模型字段

时间:2017-01-02 05:07:35

标签: python django-rest-framework

我正在尝试返回一个响应,其中包含来自2个链接模型的数据,我可以从另一个模型中获取特定字段值。模型是:

class Author(models.Model):
    author = models.CharField(max_length=200)
    author_created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('author_created',)

class Book(models.Model):
    book_name = models.CharField(max_length=200)
    author_name = models.ForeignKey(Author, on_delete=models.CASCADE)
    book_created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('book_created',)

序列化程序是:

class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = ('id', 'author')

class BookSerializer(serializers.ModelSerializer):
    name = AuthorSerializer(source='author_name')
    class Meta:
        model = Book
        fields = ('id', 'book_name','name')

我的回答显示如下:

[
    {
        "id": 1,
        "book_name": "Himu",
        "name": {
            "id": 1,
            "author": "Humayun Ahmed"
        }
    },
    {
        "id": 2,
        "book_name": "Shanta's family",
        "name": {
            "id": 2,
            "author": "Jafar Iqbal"
        }
    }
]

但我想这样表现出来:

[
    {
        "id": 1,
        "book_name": "Himu",
        "name": {
            "author": "Humayun Ahmed"
        }
    },
    {
        "id": 2,
        "book_name": "Shanta's family",
        "name": {
            "author": "Jafar Iqbal"
        }
    }
]

我如何获得此输出?

1 个答案:

答案 0 :(得分:0)

尝试类似name = AuthorSerializer(source='author_name.author')

的内容

参考:http://www.django-rest-framework.org/api-guide/fields/#source