I have 3 models with relationships as follows:
Event – 1>Many – Race – 1>Many RaceResult
If I know my Event.id I need to generate a resultset of all the related Race records and all the related RaceResult records (NB not all Race records may have RaceResult but this shouldn’t stop Race records being included).
I’m getting stuck with following the relationship backward as it only appears to accept a single row and not a query set.
This works in the shell: Race.objects.get(id=2).result_for_race.all().values()
This does not work but is closer to what I am looking to achieve: Race.objects.filter(event.id=1).result_for_race.all()
However the backward relationship Manager only appears to take a single value and not a set of objects.
I have read the documentation and tutorial but it lacks enough detail and examples to understand what is possible and what can be passed in each direction of a relationship and how they are referenced.
Advice on how to structure this query would be welcome.
Many thanks
models.py:
class Event(models.Model):
name = models.CharField(max_length=255, unique_for_year='start_date')
start_date = models.DateField()
end_date = models.DateField()
venue = models.CharField(max_length=255)
host = models.ForeignKey(
'Club',
related_name='events',
on_delete=models.PROTECT
)
theme = models.CharField(max_length=30, blank=True, null=True) # hex colour
max_entries = models.IntegerField()
def __str__(self):
return self.name + ' ' + str(self.start_date.year)
class Meta:
constraints = [
models.CheckConstraint(
check=Q(end_date__gte=F('start_date')),
name='event_ch_dates'
),
]
class Race(models.Model):
event = models.ForeignKey(
'Event',
related_name = 'race_in_event',
on_delete=models.PROTECT,
)
stage_number = models.IntegerField()
schedule = models.ForeignKey(
'Schedule',
related_name='race_schedule',
on_delete=models.PROTECT,
)
race_number = models.IntegerField()
sort_order = models.IntegerField()
group = models.IntegerField()
data = models.TextField()
class RaceResult(models.Model):
race = models.ForeignKey(
'Race',
related_name = 'result_for_race',
on_delete = models.PROTECT,
)
team1 = models.ForeignKey(
'Team',
related_name='team1_races',
on_delete=models.PROTECT
)
team2 = models.ForeignKey(
'Team',
related_name='team2_races',
on_delete=models.PROTECT
)
winning_team = models.ForeignKey(
'Team',
related_name='won_races',
on_delete=models.PROTECT
)
losing_team = models.ForeignKey(
'Team',
related_name='lost_races',
on_delete=models.PROTECT
)
team1_score = models.IntegerField()
team2_score = models.IntegerField()
finishing_order = models.TextField()
notes = models.TextField(blank=True)
views.py
def AllRacesView4(request, event_id):
render_classes = [TemplateHTMLRenderer]
resultdata = Race.objects.get(id=1).result_for_race.all()
template = loader.get_template('ksail_backend/race_list_all.html')
context = {
'resultdata': resultdata,
}
return HttpResponse(template.render(context, request))