2

I need to implement a functionality where ID of an account needs to be submitted while writing post and read additional info of an account with reading the post. How do I write the data with depth one but read data with more depth?

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',)
Puneet
  • 197
  • 1
  • 17

2 Answers2

0

As I get you want some of your fields to be read-only for example you need 'create_date' to be read but cannot be written

This is my approach:

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',)

Do The same for other readonly fileds

Serjik
  • 10,543
  • 8
  • 61
  • 70
0

you an use SerializerMethodField for this.

You don't have to modify the model. Your serializer would look like this:

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
norbert.mate
  • 302
  • 1
  • 5