Filter by ForeignKey backwards and forwards
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开发者_JAVA技巧 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!
Simplest way to do this:
Match.objects.filter(position__color='red', red_score__gt=F('blue_score'))
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:
class Team(models.Model):
name = models.CharField(max_length=100, default="", blank=True, null=True)
number = models.IntegerField()
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)
teams = models.ManyToManyField(Team, through='Position',
related_name='matches')
class Position(models.Model):
match = models.ForeignKey(Match)
color = models.CharField(max_length=5)
number = models.IntegerField()
team = models.ForeignKey(Team)
In this case, you will get few more options to simplify data access, e.g.:
if team
is your actual team and match
single match selected somewhere earlier in the code, this is valid:
team.matches.filter(red_score__gt=F('blue_score')) # all won matches of this team
match.teams.all() # teams involved in this match
精彩评论