Hello,
I have the below models:
class Play (models.Model):
event = models.ForeignKey(Event, on_delete=models.CASCADE)
time = models.TimeField(help_text="Start Time of Activity.")
duration = models.IntegerField(
help_text="Duration of the Activity in Minutes.")
teams1 = models.ManyToManyField(Team, related_name='teams1_to_teams', blank=True)
And
class Team (models.Model):
name = models.CharField(max_length=100, help_text="Team Name.")
event = models.ForeignKey(Event, on_delete=models.CASCADE)
Which means a Team is linked to an event and also Play is linked to an event. When I edit a Play record in Admin I currently see in the manytomany Team fields all possible teams regardless of event and I wanted to only show the Teams that have an event the same as Play. This is what I have in admin.py for Play:
class PlayAdmin(admin.ModelAdmin):
list_display = ('id', 'event', 'where', 'who')
search_fields = ["event"]
save_as = True
def formfield_for_manytomany(self, db_field, request, **kwargs):
if db_field.name == "teams1":
kwargs["queryset"] = Team.objects.filter(event=self.event)
return super(PlayAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)
which doesn’t work as self.event is not valid in the queryset. Please could you tell me how I get the event from Play to then filter the Team ?