Django admin more than one ForeignKey for admin.TabularInline

I am trying to implement a form with a subform in the admin section.

form = Fighter() subform = FighterFightHistory() //All of his fights 

My problem is this:

 <class 'fighters.admin.Fights'>: (admin.E202) 'fighters.FighterFightHistory' has more than one ForeignKey to 'fighters.Fighter'. 

So, how do I create a form that drops down for each foreign key ( fighter , opponent ).

2 foreign keys (see below):

  • Link to the fighter
  • Link to the opponent ( opponent )

wrestlers /models.py

 class FighterFightHistory(TimeStampedModel): event = models.ForeignKey('events.Event', null=True) fight = models.ForeignKey('fights.Fight', null=True) fighter = models.ForeignKey(Fighter, related_name='%(app_label)s_%(class)s_fighter', null=True) howitended = models.ForeignKey('fights.HowItEnded', null=True) opponent = models.ForeignKey(Fighter, related_name='%(app_label)s_%(class)s_opponent', null=True) ended_in_round = models.IntegerField(blank=True, null=True) youtube_code = models.CharField(max_length=50, null=True, blank=True) win = models.NullBooleanField(blank=True, null=True) 

wrestlers /admin.py

 class Fights(admin.TabularInline): model = FighterFightHistory extra = 30 class FighterAdmin(admin.ModelAdmin): list_display = ('name', 'history_completed', 'modified', 'active') search_fields = ['name'] inlines = [Fights, ] 
+7
django django-admin
source share
2 answers

This solved my problem (using fk_name ):

 class Fights(admin.TabularInline): model = FighterFightHistory extra = 30 fk_name = 'fighter' 
+17
source share

My first thought was that you could use ManyToMany-Fields and then limit the number of relationships to two. But then I thought that you can never be sure which Fighter-Object represents which type.

Then I briefly looked at Django-Docs and found something that should answer your problem: Django-Doc

The interesting part:

The member has two foreign keys to the Person (the person and the invitation), which makes the relationship ambiguous, and Django does not know which one to use. In this case, you must explicitly specify which Django foreign keys should use using through_fields, as in the example above.

I hope this helps you.

+2
source share

All Articles