按ForeignKey向后和向前过滤
我有 3 个模型类:
class Team(models.Model):
name = models.CharField(max_length=100, default="", blank=True, null=True)
number = models.IntegerField()
class Position(models.Model):
match = models.ForeignKey('Match')
color = models.CharField(max_length=5)
number = models.IntegerField()
team = models.ForeignKey('Team')
class Match(models.Model):
type = models.CharField(max_length=3)
number = models.IntegerField()
red_score = models.IntegerField(default=0)
blue_score = models.IntegerField(default=0)
match_events = models.TextField(max_length=1000)
使用现在的模型,我如何能够获取团队已赢得的比赛列表(即,如果团队属于红色位置,如果其比赛有一个红色位置,则将其添加到列表中) red_score > blue_score)
抱歉,如果这令人困惑。如果您有任何具体问题,我可以尝试澄清。
谢谢!
I have 3 model classes:
class Team(models.Model):
name = models.CharField(max_length=100, default="", blank=True, null=True)
number = models.IntegerField()
class Position(models.Model):
match = models.ForeignKey('Match')
color = models.CharField(max_length=5)
number = models.IntegerField()
team = models.ForeignKey('Team')
class Match(models.Model):
type = models.CharField(max_length=3)
number = models.IntegerField()
red_score = models.IntegerField(default=0)
blue_score = models.IntegerField(default=0)
match_events = models.TextField(max_length=1000)
Using the models as they are right now, how would I able to get a list of Matches a Team has won (i.e. if the Team belongs to a red Position, add it to the list if its Match has a red_score > blue_score)
Sorry if that's confusing. I can try to clarify if you have any specific questions.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
最简单的方法是:
您可能需要将
Position
模型移动到底部,以删除外键相关模型名称中的撇号。这也是使用 ManyToMany 关系的一个很好的例子:
在这种情况下,您将获得更多选项来简化数据访问,例如:
如果
team
是您的实际团队,并且match
在代码前面的某处选择了单个匹配,则这是有效的:Simplest way to do this:
You may want to move
Position
model to the bottom, to remove apostrophes from foreign key related models names.This is as well very good example to use ManyToMany relation:
In this case, you will get few more options to simplify data access, e.g.:
if
team
is your actual team andmatch
single match selected somewhere earlier in the code, this is valid: