Django ModelFormSet排除(或过滤)现有项

时间:2015-06-14 14:25:40

标签: django django-forms modelform formset

我不确定我理解modelformset_factory库的工作原理。我想向用户提供动态数量的表单,以便将新项目添加到数据库中。

我的模特是这样的:

#models.py
class Question(models.Model):
    user = models.ForeignKey(User)
    text = models.CharField(max_length=100)

class Answer(models.Model):
    question = models.ForeignKey(Question)
    text = models.CharField(max_length=100)

因此,用户可以为该问题定义问题和尽可能多的答案(选择)。

所以在我看来,我想知道他们想要添加多少个答案,并创建一个动态的表单集,如下所示:

def q_answers(request, qid, howManyAnswersMore):
    AnswerModelFormSet = modelformset_factory(Answer, fields=('question','text'), extra = howManyMore)
    formset = AnswerModelFormSet()

问题是,我的表单集包含数据库中的所有答案(因此回答问题#1的#1,q1的a2,q2的a1,q2的a2等)

但是,我只想显示带有qid参数的网址中所述问题的答案。如何过滤仅与该问题相关的答案项?

此外,我可以排除现有项目,只让用户添加新问题吗?

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以添加queryset参数来过滤显示的答案:

def q_answers(request, qid, howManyAnswersMore):
    AnswerModelFormSet = modelformset_factory(Answer, fields=('question','text'), extra = howManyMore)
    formset = AnswerModelFormSet(queryset=Transaction.objects.filter(quistion=qid))

或者您可以扩展BaseModelFormSet类并覆盖其queryset属性:

class BaseAnswerFormSet(BaseModelFormSet):
    def __init__(self, *args, **kwargs):
        super(BaseAnswerFormSet, self).__init__(*args, **kwargs)

        #create filtering here whatever that suits you needs
        self.queryset = Answer.objects.filter(question=qid)
def q_answers(request, qid, howManyAnswersMore):
    formset = modelformset_factory(Answer, formset=BaseTransactionFormSet,form=AnswerDateForm, extra=0, can_delete=False)