I have a game object that includes data from the 'Word' model. Everything works great, besides not being able to get the string of the user instead of the ID. A lot of searches have mentioned that the __str__(self): return (self.player.name)
should work, but I still get an ID in as 'player'
example of data:
[ { "game": 1, "turn": 1, "player": 1, "word": "test", "score": 18 }, { "game": 1, "turn": 2, "player": 2, "word": "test", "score": 12 } ]
would like to see:
[ { "game": 1, "turn": 1, "player": 'Bob', "word": "trend", "score": 18 }, { "game": 1, "turn": 2, "player": 'Sarah', "word": "test", "score": 12 } ]
models.py
class User(models.Model):
name = models.CharField(max_length=255)
email = models.EmailField()
class Word(models.Model):
game = models.ForeignKey(Game, on_delete=models.CASCADE)
turn = models.IntegerField()
player = models.ForeignKey(User, on_delete=models.CASCADE)
word = models.CharField(max_length=255)
score = models.IntegerField()
def __str__(self):
return str(self.player.name)
serializers.py
class WordSerializer(serializers.ModelSerializer):
class Meta:
model = Word
fields = ['game', 'turn', 'player', 'word', 'score']
class GameSerializer(serializers.ModelSerializer):
data = serializers.SerializerMethodField(read_only=True)
class Meta:
model = Game
fields = ['id', 'date' ,'data']
def get_data(self, obj):
return WordSerializer(obj.word, many=True).data
The table Word
save the player id, if you want to customize the response you can do it on the serializer level
class WordSerializer(serializers.ModelSerializer):
player_name = serializers.CharField(source='player.name')
class Meta:
model = Word
fields = ['game', 'turn', 'player', 'player_name', 'word', 'score']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.