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):
fighter
)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, ]
This solved my problem (using fk_name):
class Fights(admin.TabularInline):
model = FighterFightHistory
extra = 30
fk_name = 'fighter'
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With