ValueError:无法分配" u' http:// localhost:8000 / players / 1 /'":" Game.referee"必须是"用户"例

时间:2018-01-21 15:34:49

标签: python django django-rest-framework django-rest-viewsets

我理解这个错误的含义,只是不了解如何在请求中传递用户实例(邮递员)。

以下是我的模特。

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

和viewset是

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.

我真的应该从网址创建用户实例,还是有更优雅的方式来传递用户实例?

1 个答案:

答案 0 :(得分:0)

所以在检查CreateModelMixin后,我有了一个想法,我做了以下事情。

{{1}}