MaT
MaT

Reputation: 1606

Django Tastypie custom model method

I just start using Django with Tastypie in a Rest application with two models.

Parameters are snipped for brevity.

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)

There can be multiple score for one player. I can get all scores like this: /api/v1/score/ But how can I retrieve the scores linked with a specific player?

How can I implement that?

Thanks a lot

Upvotes: 1

Views: 294

Answers (1)

JamesO
JamesO

Reputation: 25966

You can use filtering on /api/v1/score/ so you can use /api/v1/player/?player=1 e.g.

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

or you can use ToManyField to access scores as part of the player resource, something like:

class ScoreResource(ModelResource):
    ...

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

Then you will be able to access /api/v1/player/1/ and will include the ScoresResource

Upvotes: 3

Related Questions