5

我有 3 个模型。游戏、玩家和棋子。玩家依附于游戏,而棋子依附于玩家。关系是简单的外键。

在检索游戏时,我还希望检索所有玩家的所有棋子并将它们包含在结果中。

class GameResource(ModelResource):
    class Meta:
        queryset = Game.objects.all()
        resource_name = 'game'
        allowed_methods = ['get']

class PlayerResource(ModelResource):
    game = fields.ForeignKey(GameResource, 'game')
    class Meta:
        queryset = Player.objects.all()
        resource_name = 'player'
        allowed_methods = ['get']

class PieceResource(ModelResource):
    player = fields.ForeignKey(PlayerResource, 'player')
    class Meta:
        queryset = Piece.objects.all()
        resource_name = 'piece'
        allowed_methods = ['get']

我不知道这是怎么做到的。我最初更改了 dehydrate 以便它简单地执行正确的查询,调用 django 序列化,并将其放入包中的一个新变量中。这对我来说似乎是一个障碍。查询集的序列化也被美味派再次序列化,导致它转义引号字符(呃)。

4

1 回答 1

6

解决方法如下:

class GameResource(ModelResource):
    players = fields.ToManyField('blokus.api.PlayerResource', 'player_set', full=True)
    class Meta:
        queryset = Game.objects.all()
        resource_name = 'game'
        allowed_methods = ['get']
        authorization = Authorization()


class PlayerResource(ModelResource):
    game = fields.ForeignKey(GameResource, 'game')
    pieces = fields.ToManyField('blokus.api.PieceResource', 'piece_set', full=True)

    class Meta:
        queryset = Player.objects.all()
        resource_name = 'player'
        allowed_methods = ['get']
        authorization = Authorization()


class PieceResource(ModelResource):
    player = fields.ForeignKey(PlayerResource, 'player')

    class Meta:
        queryset = Piece.objects.all()
        resource_name = 'piece'
        allowed_methods = ['get']
        authorization = Authorization()
于 2011-12-16T15:43:49.843 回答