开发者

relationship to a Django many to many relationship?

开发者 https://www.devze.com 2023-02-02 06:45 出处:网络
I\'m relatively new to Django and OO, so I may be missing something obvious, but I can\'t wrap my head around how to model the following:

I'm relatively new to Django and OO, so I may be missing something obvious, but I can't wrap my head around how to model the following:

  • I have locations.

  • I have games.

Each location can have as many games as it needs, and games can be in multiple locations (these are games as in "monopoly", the game title, not a specific instance).

This is simple enough to model with a m2m relationship:

class Location(models.Model):
    name = models.CharField(max_length=300)
    city = models.CharField(max_length=300)
    [ etc etc ]
    games = models.ManyToManyField('Game', related_name='locations', blank=True)


class Game(models.Model):
    name = models.CharField(max_length=300)
    manufacturers = models.ForeignKey('Manufacturer')
    [ etc etc ]

I also have the usual Django user model.

Now, what I'm trying to add to this relationship is the concept of scores.

Users should be able to enter their scores for a game located in a particular location. I should then be able to show, say, the top 10 scores for each game in a location but also the top 10 scores gl开发者_如何学运维obally for a game across all locations.

So, basically there should be a score linked to a user, a game and a location.

It looks to me like it should be some type of relationship to the relationship itself. I looked at extra fields on m2m relationships and at intermediary models but I can't figure out a way to do this properly.

Any pointers gladly appreciated.

Thanks!


If you want to link to the releationship between Game & Location you need to create intermediary model. Here is a sample code

class Location(models.Model):
    name = models.CharField(max_length=300)
    city = models.CharField(max_length=300)
    [ etc etc ]
    games = models.ManyToManyField('Game', related_name='locations', blank=True, through='GameLocation')


class Game(models.Model):
    name = models.CharField(max_length=300)
    manufacturers = models.ForeignKey('Manufacturer')
    [ etc etc ]

class GameLocation(models.Model):
    game = models.ForeignKey(Game)
    location = models.ForeignKey(Location)
    # some other filed like for example date

class Score(models.Model):
    user = models.ForeginKey('user')
    gamelocation = models.ForeginKey('GameLocation')
    score = models.DecimalField(max_digits=5, decimal_places=2)

Btw. I would rename your Game to GameType and then call GameLocation simple a Game.

0

精彩评论

暂无评论...
验证码 换一张
取 消