Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django admin more than one ForeignKey for admin.TabularInline

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

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

My issue is the following:

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

So how do I make the form show a drop down for each foreign key (fighter, opponent).

The 2 foreign key are (see below):

  • A link to the fighter (fighter)
  • A link to the opponent (opponent)

fighters/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)

fighters/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, ]
like image 355
Yannick Avatar asked Sep 23 '14 20:09

Yannick


2 Answers

This solved my problem (using fk_name):

class Fights(admin.TabularInline):
    model = FighterFightHistory
    extra = 30
    fk_name = 'fighter'
like image 108
Yannick Avatar answered Nov 04 '22 09:11

Yannick


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

Then I had a short look into the Django-Docs and found something that should answer your problem: Django-Doc

The interesting part is:

Membership has two foreign keys to Person (person and inviter), which makes the relationship ambiguous and Django can’t know which one to use. In this case, you must explicitly specify which foreign keys Django should use using through_fields, as in the example above.

I hope that this helps you.

like image 2
Stefan Wegener Avatar answered Nov 04 '22 08:11

Stefan Wegener