Django - 在管理界面中过滤ForeignKey下拉菜单

时间:2014-08-05 12:54:07

标签: django django-models django-admin

当我访问活动结果表单(见下图)时,从管理界面我希望战斗下拉菜单只显示相关活动的战斗。

enter image description here

使用此网址/ events / eventresult / 4 / 我怎样才能表明它只展示了活动4的战斗。而不是所有活动的所有战斗。

管理模式

class EventResultAdmin(admin.ModelAdmin):
    list_display = ('event', 'fight', 'howitended', 'winner', 'ended_in_round', 'fight_started', 'fight_ended',)

    search_fields = ['event__name']

战斗模型

class Fight(TimeStampedModel):
    event = models.ForeignKey(Event, null=True, related_name='fights')
    fighter = models.ForeignKey(Fighter, related_name='%(app_label)s_%(class)s_fighter', null=True)
    fightstatus = models.ForeignKey('fights.FightStatus', null=True, blank=True)
    opponent = models.ForeignKey(Fighter, related_name='%(app_label)s_%(class)s_opponent', null=True)

    folder_name = models.CharField(max_length=500, blank=True, null=True)
    fight_highlights = models.CharField(max_length=500, blank=True, null=True)
    fight_order = models.IntegerField(blank=True, null=True)
    name = models.CharField(max_length=500, blank=True)
    post_fight_interview = models.CharField(max_length=500, blank=True, null=True)
    show_fact = models.NullBooleanField(default=True, null=True)
    total_round = models.IntegerField(blank=True, null=True)
    view_count = models.IntegerField(default=0, null=True)

    def __unicode__(self):
        return '{} vs {}'.format(self.fighter.name, self.opponent.name)

1 个答案:

答案 0 :(得分:1)

找到解决方案

if db_field.name == 'fight':
    event_result_id = request.META['PATH_INFO'].strip('/').split('/')[-1]
    event = EventResult.objects.get(pk=event_result_id)
    kwargs['queryset'] = Fight.objects.filter(event_id=event.event_id)