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

标签 python django django-admin

考虑一款人们可以参加比赛的应用。

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

  1. 一场比赛可能有很多问题
  2. 一道题不能出现在多场比赛中

在我的 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

任何能达到预期结果的提示、建议或引用将不胜感激。

最佳答案

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)

关于python - 在 Django Admin 中限制/过滤外键选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49401465/

相关文章:

java - Jython 作为 Java 游戏的游戏内控制台

python - 从 Django 1.7 到 1.8 的自动提交迁移

python - pip使用Python 2.5并且需要使用Python 2.7

django - 在 Django Admin 中过滤 ManyToMany 框

python - Django 管理员将上下文添加到index.html

python - 尝试对字典中的键值对求和

python - Django FileField with upload_to 在运行时确定

python - 使用 heapq.merge 编写排序输出的奇怪 Python 版本相关行为

python - 单个 django 应用程序使用多个 sqlite3 文件作为数据库

python - Django 数组字段。如何通过 django admin 保存嵌套的时间数组?