如何在Django Rest Framework中使用ModelSerializer编写平面和读取?

时间:2016-01-17 17:21:07

标签: python django django-rest-framework

我需要实现一种功能,其中在撰写帖子时需要提交帐户的ID,并在阅读帖子时阅读帐户的其他信息。如何使用深度1编写数据但是读取更深入的数据?

ModelSerializers:

class PostSerializer(serializers.ModelSerializer):
    author = UserSerializer(required=False, allow_null=True)
    class Meta:
        model = Post
        fields = ('id', 'author', 'message', 'rating', 'create_date', 'close_date',)

class UserSerializer(serializers.ModelSerializer):
   class Meta:
       model = User
       fields = ('id', 'username', 'full_name',)

2 个答案:

答案 0 :(得分:0)

因为我想让你的某些字段成为只读字段,例如你需要' create_date'被阅读但无法写入

这是我的方法:

models.py

# This extra modification done as late comments 
class Post(models.Model):
  ...
  def username(self):
     return self.author.username

  def full_name(self):
     return self.author.full_name

Serializer.py

class PostSerializer(serializers.ModelSerializer):
    # author = UserSerializer(required=False, allow_null=True)  # Don't define this
    create_date_read_only = serializers.DateTimeField(required = False, read_only = True, source = 'create_date')
    class Meta:
        model = Post
        # username, full_name added to fileds tuple
        fields = ('id', 'author', 'username','full_name','message', 'rating', 'create_date_read_only', 'close_date',)

对其他只读文件执行相同的操作

答案 1 :(得分:0)

为此使用SerializerMethodField

您不必修改模型。你的序列化器看起来像这样:

class PostSerializer(serializers.ModelSerializer):
    my_username = serializers.SerializerMethodField()

    class Meta:
        model = Post
        fields = ('id', 'author', 'my_field'...)

    def get_my_username(self, obj):
        return obj.user.author.username