我明白这个错误在说什么,只是不明白如何在请求中传递用户实例(邮递员)。
以下是我的模型。
class Game(models.Model):
referee = models.ForeignKey(User, on_delete=models.CASCADE, related_name='referee')
player_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='opponent_1')
player_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='opponent_2')
attacker = models.ForeignKey(User, on_delete=models.CASCADE, related_name='attacker')
status = models.CharField(max_length=20, choices=GAME_STATUS, default='QUEUED')
game_type = models.CharField(max_length=20, choices=GAME_TYPE, default='LEAGUE')
序列化器。
class GameSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Game
fields = ('__all__')
并且视图集是
class GameViewSet(viewsets.ModelViewSet):
queryset = Game.objects.all()
serializer_class = GameSerializer
直到这里"u'http://localhost:8000/players/1/'"
工作正常。
只要我跟着。
def create(self, request):
game = Game.objects.create(
referee = request.data.get('referee', request.user),
player_1 = request.data.get('player_1', None),
player_2 = request.data.get('player_2', None),
attacker = request.data.get('attacker', None),
status = request.data.get('status', None),
game_type = request.data.get('game_type', None)
)
game.save()
return game
相同的 API 调用引发以下错误
ValueError: Cannot assign "u'http://localhost:8000/players/1/'": "Game.referee" must be a "User" instance.
我真的应该从 url 创建用户实例还是有更优雅的方式来传递用户实例?