我正在使用Django。我有一个Fixture模型,看起来像:
class Fixture(models.Model):
home_team = models.ForeignKey(Team, related_name="home_fixture_set")
home_score = models.IntegerField(max_length=2, blank=True, null=True)
away_team = models.ForeignKey(Team, related_name="away_fixture_set")
away_score = models.IntegerField(max_length=2, blank=True, null=True)
when = models.DateTimeField()
我的团队模型类似于:
class Team(models.Model):
name = models.CharField(max_length=60)
club = models.ForeignKey(Club)
我可以通过home_fixture_set related_name访问特定团队的“home”灯具列表:
my_team.home_fixture_set.all()
我可以类似地访问“离开”灯具。但是,我不知道如何将两者结合起来并得到这支球队参与的所有赛程的清单?例如:
my_team.home_and_away_fixture_set.all()
请注意,home_and_away_fixture_set必须返回一个查询集,以便我可以对其进行过滤:
my_team.home_and_away_fixture_set.filter(when__lte=datetime.datetime.now())
是否可以通过模型查询API执行此操作?如果没有,是否可以通过Manager.raw()查询轻松地完成此操作?
由于 杰
答案 0 :(得分:2)
from django.db.models import Q
home_and_away_fixtures = Fixtures.objects.filter(Q(home_team=team)|Q(away_team=team))
或修改:
home_and_away_fixtures = my_team.home_fixture_set.all() | my_team.away_fixture_set.all()
thx shadfc:单个查询以及