在Django Admin中限制/过滤外键选择

时间:2018-03-21 08:34:10

标签: python django django-admin

考虑一个人们可以参加比赛的应用程序。

我已准备好ContestContestProblem模型。我想为比赛提供以下功能:

  1. 比赛可能有很多问题
  2. 问题不能出现在多个竞赛中
  3. 在我的models.py中,我有:

    class ProblemsInContest(CreateUpdateDateModel):
        contest = models.ForeignKey(Contest)
        problem = models.ForeignKey(ContestProblem)
    
        class Meta:
            verbose_name = "Problem in Contest"
            verbose_name_plural = "Problems in Contest"
    
        def __str__(self):
            return "{problem}".format(problem=self.problem)
    

    在我的admin.py中,我有:

    class ContestProblemInline(admin.TabularInline):
        model = ProblemsInContest
        extra = 1
    
    
    class ContestAdmin(admin.ModelAdmin):
    
        inlines = [
            ContestProblemInline,
        ]
    

    这就是我的管理表单的外观: enter image description here

    我正在使用Django Admin为比赛添加问题。问题在于,在问题下拉列表中,它向我展示了所有ContestProblem,但我想将其限制为仅出现在任何其他竞赛中的ContestProblem

    任何有关达到预期效果的提示或建议或参考资料都将受到高度赞赏。

1 个答案:

答案 0 :(得分:3)

class ContestProblemInline(admin.TabularInline):

    model = ProblemsInContest

    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):

        field = super(RoomInline, self).formfield_for_foreignkey(db_field, request, **kwargs)

        if db_field.name == 'your_field_name':
            if request._obj_ is not None:
                field.queryset = field.queryset.filter(your_field_name = request._obj_)  
            else:
                field.queryset = field.queryset.none()

        return field



class ContestAdmin(admin.ModelAdmin):

    inlines = (ContestProblemInline,)

    def get_form(self, request, obj=None, **kwargs):
        # just save obj reference for future processing in Inline
        request._obj_ = obj
        return super(ContestAdmin, self).get_form(request, obj, **kwargs)