考虑一个人们可以参加比赛的应用程序.
我准备好了竞赛和竞赛问题模型.我想为比赛提供以下功能:
>比赛可能有很多问题
>问题不能出现在多个比赛中
在我的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.
任何提示或建议或参考,以达到预期的结果将受到高度赞赏.
最佳答案
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,obj=None,**kwargs):
# just save obj reference for future processing in Inline
request._obj_ = obj
return super(ContestAdmin,self).get_form(request,obj,**kwargs)