Django模型关系

wr98u20j  于 2022-12-01  发布在  Go
关注(0)|答案(2)|浏览(120)

我们的想法是有两种模式:组和玩家。我的目标是有不同的组,每个组都有玩家。每个玩家可以属于一个或多个组。在一个组中,每个玩家都有一些积分,但同一个玩家在另一个组中可以有不同的积分。

class Player(models.Model):
    username = models.CharField(max_length = 200)
    won_games = models.IntegerField(default=0)

class Point(models.Model):
    player = models.ForeignKey(Player, on_delete=models.PROTECT, related_name='points')
    val = models.IntegerField()
    group =  models.ForeignKey(Group, on_delete=models.PROTECT, related_name='points')

class Group(models.Model):
    id = models.CharField(max_length = 200)
    players = models.ManyToManyField(Player,related_name="groups")
    points = models.ManyToManyField(Point)

我很困惑,因为我不知道如何让一个球员在A组有“x”点(例如),也有“y”点在B组。我希望能够显示一个组的数据,为每个组,显示其成员和他们的点。

clj7thdc

clj7thdc1#

你可以告诉Django在该字段中使用through参数来为多对多关系使用自定义模型,方法如下:

class Player(models.Model):
    username = models.CharField(max_length = 200)
    won_games = models.IntegerField(default=0)

class Group(models.Model):
    id = models.CharField(max_length = 200)
    players = models.ManyToManyField(Player, related_name="groups", through='Point')

class Point(models.Model):
    player = models.ForeignKey(Player, on_delete=models.PROTECT, related_name='points')
    group =  models.ForeignKey(Group, on_delete=models.PROTECT, related_name='points')

Django文档包含了一个关于这个主题的例子:https://docs.djangoproject.com/en/4.1/topics/db/models/#extra-fields-on-many-to-many-relationships

gr8qqesn

gr8qqesn2#

您可能需要一个带有额外字段的中间表。类似于:

from django.db import models

class Player(models.Model):
    username = models.CharField(max_length = 200)
    won_games = models.IntegerField(default=0)

    def __str__(self):
        return self.username

class Group(models.Model):
    name = models.CharField(max_length=128)
    players= models.ManyToManyField(Player, through='Point')

    def __str__(self):
        return self.name

class Point(models.Model):
    player = models.ForeignKey(Player, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    point = models.IntegerField()

相关问题