Skip to content

AttributeError when a ParentalKey related manager is used as the queryset for a ModelChoiceField #160

Open
@bcdickinson

Description

@bcdickinson

Bug

FakeQuerySet doesn't have a _prefetch_related_lookups member, so Django throws an attribute error when using it as the queryset kwarg to a ModelChoiceField, here: https://github.com/django/django/blob/3.2.12/django/forms/models.py#L1167

My guess at a solution at this moment in time is to just add _prefetch_related_lookups = () to FakeQuerySet.__init__(), but I'm not 100% sure that's the right answer.

Context

I'm creating a QuestionPage that has multiple choice questions on it. QuestionPages have many Questions which in turn have many Answers. I generate a Form to use on the page and that works fine, but it breaks when I'm previewing the page with the following error:

'FakeQuerySet' object has no attribute '_prefetch_related_lookups'

Here's a sketch:

class QuestionPage(Page):
  ...
  
  content_panels = [
    ...,
    InlinePanel('questions'),
  ]


class Question(ClusterableModel):
  question_page = ParentalKey(QuestionPage, related_name='questions')
  ...

  panels  = [
    InlinePanel('answers'),
    ...
  ]
  

class Answer(models.Model):
  question = ParentalKey(Question, related_name="answers")
  ...


class QuestionPageForm(forms.Form):
  def __init__(self, *args, question_page: QuestionPage, **kwargs):
    super().__init__(*args, **kwargs)

    for question in question_page.questions.all():
      self.fields[f"question-{question.pk}"] = forms.ModelChoiceField(
        queryset=question.answers.all(),  # This seems to be what causes the AttributeError during previews
      )

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions