Я пытаюсь добавить метод свойства класса в модель Game, однако он не отображается на веб-интерфейсе, когда я вызываю game.owner_username.
Модель:
class Game(models.Model):
location = models.CharField(max_length=100)
players = models.ManyToManyField(User)
kickoff_time = models.DateTimeField()
created_at = models.DateTimeField(auto_now_add=True)
max_player_count = models.IntegerField(null=True)
goal_type = models.CharField(max_length=100)
notes = models.CharField(max_length=300, null=True)
status = models.CharField(max_length=6)
owner = models.ForeignKey(
User, related_name="games", on_delete=models.CASCADE, null=True)
@property
def owner_username(self):
return self.owner.username
РЕДАКТИРОВАТЬ:
Исправлено путем добавления этой строки кода в сериализатор:
owner_username = serializers.ReadOnlyField()
Так что теперь мой сериализатор:
class GameSerializer(serializers.ModelSerializer):
# Serializers take the data which is on our server and convert it into a
# format which can be read by other technologies (in our case JSON).
# When data is sent TO the server it does the opposite, converting data
# into a format our server can handle.
owner_username = serializers.ReadOnlyField()
class Meta:
model = Game
fields = "__all__"