开发者

Django: model with multiple related fields of the same type

开发者 https://www.devze.com 2023-02-26 06:18 出处:网络
I am using Django. I have a Fixture model, which looks something like: class Fixture(models.Model): home_team = models.ForeignKey(Team, related_name=\"home_fixture_set\")

I am using Django. I have a Fixture model, which looks something like:

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()

I have a Team model that looks something like:

class Team(models.Model):
    name = models.CharField(max_length=60)
    club = models.ForeignKey(Club)

I am able to access a list of "home" fixtures for a specific team through the home_fixture_set related_name:

my_team.home_fixture_set.all()

I can access the "away" fixtures similarly. However, I do not know how I combine the two and get the list of all fixtures this team is involved in? Eg:

my_team.home_and_away_fixture_set.all()

Note that home_and_away_fixture_set must return a queryset, so that I can filter on it:

my_开发者_开发知识库team.home_and_away_fixture_set.filter(when__lte=datetime.datetime.now())

Is it possible to do this through the model query API? If not, is it possible to accomplish this reasonably easily through a Manager.raw() query?

Thanks Jay


from django.db.models import Q
home_and_away_fixtures = Fixtures.objects.filter(Q(home_team=team)|Q(away_team=team))

or edit:

home_and_away_fixtures = my_team.home_fixture_set.all() | my_team.away_fixture_set.all()

thx shadfc: single query as well

0

精彩评论

暂无评论...
验证码 换一张
取 消