我建立了一个在线测试系统,我目前有两个表:
class Answer(models.Model):
ID = models.IntegerField(primary_key = True)
answer = models.TextField()
class Question(models.Model):
ID = models.IntegerField(primary_key = True)
.....
answer = ForeinKey(Answer)
我有模型管理员
^{pr2}$我正在为它做管理网站。我想要的是,每次用户访问问题时,网站只显示与之相关的适当答案,用户可以编辑答案(弹出答案管理窗口)。我曾试图重写QuestionAdmin
中的formfield_for_foreignkey(self, db_field, request, **kwargs)
和change_view(self, request, object_id, extra_context=None)
,以缩小查询集的范围并将相关答案传递给模板,但由于我不知道在Answer.objects.filter(ID = ???)
中放入什么,所以没有用。有什么想法吗?也试过用表格。在
更新: 我做了这个:用
class QuestionForm(forms.ModelForm):
class Meta:
model = Question
def __init__(self, *args, **kwargs):
super(QuestionForm,self).__init__(*args,**kwargs)
self.fields['answer'].queryset = Answer.objects.filter(ID = self.instance.answer.ID)
要覆盖QuestionAdmin中的表单并向模板添加上下文:
def change_view(self, request, object_id, extra_context=None):
extra_context = extra_context or {}
extra_context['ID'] = object_id
return super(QuestionAdmin, self).change_view(request, object_id,
extra_context=extra_context)
它可以工作,但它要求答案ID与引用它的问题ID相同,有没有更好的方法?在
我想你在找this。你可以过滤除ID之外的其他键。 您的代码可能是
Answer.objects.filter(question = myquestion)
{你考虑过使用^ a1的功能而不是^管理?在
模型.py
管理员py
^{pr2}$这样,您实际上只需要一个管理类(对于您的问题模型),答案总是在适当的地方。只是想一想,这是我在项目中经常用到的东西。在
一种可能的方法是使用modelchoicefield。在
像这样:
相关问题 更多 >
编程相关推荐