考虑一个人们可以参加比赛的应用程序。
我已准备好Contest
和ContestProblem
模型。我想为比赛提供以下功能:
在我的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,
]
我正在使用Django Admin为比赛添加问题。问题在于,在问题下拉列表中,它向我展示了所有ContestProblem
,但我想将其限制为仅出现在任何其他竞赛中的ContestProblem
。
任何有关达到预期效果的提示或建议或参考资料都将受到高度赞赏。
答案 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)