gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 18:49:28 26 4
gpt4 key购买 nike

我有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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com