I created models as below; Team model stores different team names, Tournament model is used to create a tournament and add teams into it and finally Game model where I select a tournament, add two teams and create a game. My problem is in Admin panel, while creating a game after selecting a tournament I have to select two teams from the choice list, instead of getting just the teams participating in the Tournament, I am getting all the available teams from the Team model.
class Team(models.Model):
name = models.CharField(max_length=30) # Ind, Pak, Aus, Sri, Eng
class Tournament(models.Model):
name = models.CharField(max_length=50) # Asia Cup:
teams = models.ManyToManyField(Team) # Ind, Pak, Sri
class Game(models.Model):
name = models.CharField(max_length=50)
tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE) # Asia Cup
teams = models.ManyToManyField(Team) # Expected: Ind, Pak, Sri
My Admin panel customization:
class TeamInline(admin.TabularInline):
model = Game.teams.through
class Game(admin.ModelAdmin):
fields = ['name']
inlines = [TeamInline]

Django Admin Inline use ModelForm to render it's content(described in doc) so you need to override the child
form.After that set custom
formsetto pass parent to child form, and in the child form override initial value with init within form docparent_objectrefer to the Game instance when you editingthe way to get parent instance in Inline Admin Form come from this answer