Python 基于第二个表字段的Django反向外键
我在Django有以下两张桌子Python 基于第二个表字段的Django反向外键,python,sql,django,foreign-keys,Python,Sql,Django,Foreign Keys,我在Django有以下两张桌子 class TeamSubscriptions(models.Model): user = models.ForeignKey(User, unique=True) soccer_team = models.ForeignKey(SoccerTeam) .... .... class Meta: db_table = 'soccer_team_subscriptions' class MatchSubsc
class TeamSubscriptions(models.Model):
user = models.ForeignKey(User, unique=True)
soccer_team = models.ForeignKey(SoccerTeam)
....
....
class Meta:
db_table = 'soccer_team_subscriptions'
class MatchSubscriptions(models.Model):
team_subscriber = models.ForeignKey(TeamSubscriptions, related_name='soccer_user_matches')
soccer_match = models.IntegerField(db_index=True)
winning_team_guess = models.CharField(max_length=50, default='')
...
...
class Meta:
db_table = 'soccer_game_subscriptions'
unique_together = ("team_subscriber", "soccer_match")
我想从Teamsubscriptions
获取所有订阅者。对于所有这些,我想找到相应的
MatchSubscriptions
中具有特定soccer\u比赛
ID的行。其目的是从第二个表中获取某些特定soccer\u比赛
ID的获胜团队
对于特定的
soccer\u比赛
ID..,是否有任何方法可以执行此操作(反向外键)是的,您可以使用Django的ORM执行此操作:
TeamSubscriptions.objects.filter(matchsubscriptions__soccer_match_id=YOUR_ID)
查看Django关于使用关系查找的信息
通常,如果要在查询集中进行筛选,可以使用默认值等于FK的值的,在您的示例中,它是matchsubscriptions\u set
,您只需删除\u set
,因为它是在使用查询集时由Django生成的