Pipsqweek
Pipsqweek

Reputation: 404

Proper model relationship for Player and Prizes?

I seem to have a mental impediment when it comes to abstracting model relationships.

I want to have prizes available to players. Not all players have prizes, but a list should be available if needed.

This is what I have so far:

class Prize(models.Model):
    player = models.ForeignKey(Profile, related_name="gifts", null=True, blank=True)

I should be able to do Profile.prizes and get a list if any exists, but ...

a) this is probably the wrong relationship b) this is probably backwards...

I just need some slight adjustment to get back on track here. Thanks.

Upvotes: 1

Views: 30

Answers (2)

Akash Wankhede
Akash Wankhede

Reputation: 618

I would suggest this way:

class Prize(models.Model):
    # write here prize model fields


class Player(models.Model):
    prizes = models.ManyToManyField(Prize, blank=True)

By using this approach, u can get all the prizes a player have,

player = Player.objects.get(id=123)
prizes = player.prizes.all()

and you can also find, how many players got any specific prize,

prize = Prize.objects.get(id=123)
players = prize.player_set.all()

Upvotes: 0

alioguzhan
alioguzhan

Reputation: 7917

You can use ManyToManyField for Player model:

class Player(models.Model):
    prizes = models.ManyToManyField("Prize")


class Prize(models.Model):
    # prize_name = ...
    # prize_amount = ...

Then you can get all prizes for one specific player with:

player = Player.objects.get(id=12)
player.prizes.all()

For more information and examples about ManyToMany Relations, check here

Upvotes: 3

Related Questions