使用外键字段获取自定义序列化模型的最简单方法是什么

时间:2014-09-05 13:24:20

标签: python django serialization django-models django-rest-framework

我正在寻找一种从Django REST框架继承rest_framework.serializers.ModelSerializer的简单方法,以便它将序列化为外键模型字段的特殊字典,其中包含模型类的名称和id值,而不仅仅是整数/ 首要的关键。这适用于不同的模型。

# models.py
class Author(models.Model):
    name = models.CharField(max_length=255)

class Book(models.Model):
    book_written_by = models.ForeignKey(Author)

class Song(models.Model):
    song_written_by = models.ForeignKey(Author)

# serializers.py
class CustomSerializer(serializers.ModelSerializer):
    # What to do here? #

class BookSerializer(CustomSerializer):
    class Meta:
        model = Book

class SongSerializer(CustomSerializer):
    class Meta:
        model = Song

我想得到以下结果:

kleist = Author.objects.create(name='Kleist')
some_book = Book.objects.create(author=kleist)
BookSerializer(some_book).data == {'id': 1, 'book_written_by': {'Author': 1}}  # Returns True

我试图覆盖get_related_field()并将PrimaryKeyRelatedField更改为CustomPrimaryKeyRelatedField,我尝试覆盖to_native()但我无法访问模型字段及其对象本身,只能访问pk值。

1 个答案:

答案 0 :(得分:2)

你所需要的东西当然是可以实现的,但它确实违反惯例,所以我个人投反对票。然而,实现所需的方法是使用SerializerMethodField

class BookSerializer(serializers.ModelSerializer):
    book_written_by = serializers.SerializerMethodField('get_author')

    class Meta:
        model = User

    def get_author(self, obj):
        return {'Author': obj.book_written_by.pk}

这将返回您想要的确切输出。如果您决定坚持惯例,我更喜欢这样的输出:

{'id': 1, 'book_written_by': {'id': 1, 'name': 'somebody'}}

以下序列化程序会为您返回:

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

class BookSerializer(serializers.ModelSerializer):
    book_written_by = AuthorSerializer()