django - 如何在 django-tastypie 中包含不直接(通过另一个资源)的反向关系?

标签 django api tastypie

我有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']

我不知道这是如何完成的。我最初更改了脱水,以便它只是执行正确的查询,调用 django 序列化,并将其放入包中的一个新变量中。这对我来说似乎是个陷阱。查询集的序列化也被tastypie 再次序列化,导致它转义引号字符(urgh)。

最佳答案

解决方法如下:

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()

关于django - 如何在 django-tastypie 中包含不直接(通过另一个资源)的反向关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8525811/

相关文章:

javascript - Dajaxice javascript 核心文件未被解析

django - 如何获取序列化器内的序列化器字段值

javascript - 尝试使用 googlemaps api 和 javascript 查找两个 LatLng 对象之间的距离

php - 从 Patreon API 获取订阅者数据

python - 资源没有可用的反序列化方法

Python - 如何在用户的时间线中搜索?

python - 字段中项目的 Django 计数

python - 在 python 中使用 azure REST api 将 Runbook 创建为草稿时,我遇到了错误...!

django - Tastypie 自定义字段

python - tastypie PUT 有效但 POST 无效