【问题标题】:Django Tastypie custom model methodDjango Tastypie 自定义模型方法
【发布时间】:2013-04-18 01:30:26
【问题描述】:

我刚开始在带有两个模型的 Rest 应用程序中使用 Django 和 Tastypie。

为简洁起见,参数被截断。

class Player(models.Model):

    pseudo = models.CharField(max_length=32, unique=True)

class Score(models.Model):

    level = models.IntegerField()
    score = models.IntegerField()
    player = models.ForeignKey(Player)

一个玩家可以有多个分数。 我可以像这样得到所有分数:/api/v1/score/ 但是如何检索与特定玩家关联的分数?

我该如何实现?

非常感谢

【问题讨论】:

    标签: django django-models tastypie


    【解决方案1】:

    您可以在/api/v1/score/ 上使用filtering,这样您就可以使用/api/v1/player/?player=1,例如

    class ScoreResource(ModelResource):
        class Meta:
            ...
            filtering = {'player':ALL_WITH_RELATIONS}
    

    或者您可以使用ToManyField 作为玩家资源的一部分来访问分数,例如:

    class ScoreResource(ModelResource):
        ...
    
    class PlayerResource(ModelResource):
        score = fields.ToManyField(ScoreResource, 'scores', full=True)
    

    然后您将能够访问/api/v1/player/1/ 并将包括ScoresResource

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-24
      • 2013-03-09
      • 2019-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-06
      相关资源
      最近更新 更多