简体   繁体   English

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

[英]Limit/Filter Foreign Key Choices in Django Admin

Consider an app where people can participate in a contest. 考虑一个人们可以参加比赛的应用程序。

I have a Contest and ContestProblem Model ready. 我准备好了ContestContest ContestProblem模型。 I want to have following features for the contest: 我想为比赛提供以下功能:

  1. A contest can have many problems 比赛可能有很多问题
  2. A problem can not appear in more than one contest 一个问题不能出现在多个比赛中

In my models.py , I have: 在我的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)

In my admin.py, I have: 在我的admin.py中,我有:

class ContestProblemInline(admin.TabularInline):
    model = ProblemsInContest
    extra = 1


class ContestAdmin(admin.ModelAdmin):

    inlines = [
        ContestProblemInline,
    ]

This is how my Admin Form look: 这就是我的管理表单的外观: 在此输入图像描述

I am using Django Admin to add problems to a contest. 我正在使用Django Admin为比赛添加问题。 The problem being the fact that in the Problem dropdown, it shows me all the ContestProblem but I want to limit it to only those ContestProblem which does not appear in any other contest. 问题在于,在问题下拉列表中,它向我展示了所有ContestProblem但我想将其限制为仅出现在任何其他比赛中没有出现的ContestProblem

Any hints or advice or references to achieve the desired results will be highly appreciated. 任何提示或建议或参考,以达到预期的结果将受到高度赞赏。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM