Django如何生成一个反向外键引用

2024-09-25 00:35:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我建立了一个在线测试系统,我目前有两个表:

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相同,有没有更好的方法?在


Tags: 答案answerselfidobjectmodelsrequestcontext
3条回答

我想你在找this。你可以过滤除ID之外的其他键。 您的代码可能是Answer.objects.filter(question = myquestion)

{你考虑过使用^ a1的功能而不是^管理?在

模型.py

class Question(models.Model):
   text = models.TextField()

class Answer(models.Model):
   text = models.TextField()
   question = models.ForeignKey(Question)

管理员py

^{pr2}$

这样,您实际上只需要一个管理类(对于您的问题模型),答案总是在适当的地方。只是想一想,这是我在项目中经常用到的东西。在

一种可能的方法是使用modelchoicefield。在

像这样:

def get_question_admin_form(the_q):
    class QuestionAdminForm(forms.ModelForm):
        answers = forms.ModelChoiceField(label="Answers",
                queryset=Question.objects.filter(pk=the_q.pk).answer_set.all())

        # ... other fields

        class Meta:
            model = Question

    return QuestionAdminForm

class QuestionAdmin(admin.modelAdmin):
    model = Question

    def get_formset(self, request, obj=None, **kwargs):
        if obj is not None:
            self.form = get_question_admin_form(obj)
        return super(QuestionAdmin, self).get_formset(request, obj, **kwargs)

相关问题 更多 >