Django多对多关系查询反转

2024-04-28 16:52:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我和django有个问题,我想用什么关系,我对这个任务很困惑。你知道吗

我有两张桌子,一张桌子是ball,另一张桌子是体育场,在我的问题中,一个体育场可能有很多球,一个球可能有很多体育场。你知道吗

这是我的模型:

class ball(models.Model):
    code_ball=models.CharField(max_length=150,unique=True)
    description_ball = models.CharField(max_length=254)
    made_country_ball= models.CharField(max_length=254)
    f_ball= models.CharField(max_length=254)
    rel= models.ManyToManyField(stadium)

class stadium(models.Model):
    code_stadium=models.CharField(max_length=150,unique=True)
    description_stadium = models.CharField(max_length=254)
    made_country_stadium= models.CharField(max_length=254)
    andress_stadium= models.CharField(max_length=254)
    team_stadium= models.CharField(max_length=254)

我的问题是如何创建查询视图来在html模板中显示这些内容? 例如,在某些html页面中,需要显示表stadium中的所有详细信息,以及表balls中带有description_bal的所有或第一个code_ball。你知道吗

我不知道该怎么做,因为我没有表ball到表stadium的外键,用某种方式我需要反转关系来创建一个新的查询,知道怎么做吗?你知道吗


Tags: truemodel关系modelscodedescriptionlengthmax
2条回答

必须有两个表的关联实体。你知道吗

class ball(models.Model):
    code_ball=models.CharField(max_length=150,unique=True)
    description_ball = models.CharField(max_length=254)
    made_country_ball= models.CharField(max_length=254)
    f_ball= models.CharField(max_length=254)
    rel= models.ManyToManyField(stadium, through='StadiumBall')

class stadium(models.Model):
    code_stadium=models.CharField(max_length=150,unique=True)
    description_stadium = models.CharField(max_length=254)
    made_country_stadium= models.CharField(max_length=254)
    andress_stadium= models.CharField(max_length=254)
    team_stadium= models.CharField(max_length=254)

class StadiumBall(models.Model):
    stadium = models.ForeignKey(stadium, on_delete=models.CASCADE)
    ball = models.ForeignKey(ball, on_delete=models.CASCADE)

Here is a documentation

如果您想拥有许多字段的全部功能,您应该定义一个through表docs。这不会改变任何事情,但会向你展示幕后真正发生的事情。所以你就可以用Foreignkey关系来做你想要的。你知道吗

相关问题 更多 >