[Django]-How to add serializers.RelatedField() to Meta class fields in django rest framework

3πŸ‘

βœ…

It is really easy. You can use your related_name which you defined in your model (team). It would be better rename this field to players. You can define Serializer for Player as you did and then in the field you add related_name. In your case team (or players). And then in Team serializer you add serializer for players (you can add players if you define them as related_name).

In models.py:

class Player(models.Model):
    name = models.CharField(max_length=50)
    age = models.IntegerField(null=True)
    inMarket = models.BooleanField(default=False)
    lastInMarket = models.DateTimeField(null=True)

    team = models.ForeignKey(Team, null=True, on_delete=models.DO_NOTHING, related_name='players')

In the serializers.py:

class PlayersSerializer(serializers.ModelSerializer):
    # you don't need RelatedField to Team because players will be under the team
    team = serializers.RelatedField(read_only=True)

    class Meta:
        model = Player
        fields = ('id', 'name', 'age', 'position', 'team')

    def create(self, validated_data):
        pass

    def update(self, instance, validated_data):
        pass

class TeamSerializer(serializers.ModelSerializer):
    players = PlayerSerializer(read_only=True, many=True)

    class Meta:
        model = Team
        fields = ('name', 'user', 'competitions', 'players')

    def create(self, validated_data):
        return Team.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.players = validated_data
        return instance

Send a comment if you will have some problem with implementation and tell me if it is working as you expect.

πŸ‘€Bulva

Leave a comment