模型尚未加载

Models aren't loaded yet

我尝试获取 ProgramPage 的所有页面,其中字段 program_types 具有特定的 pk 在我添加这个之前一切都很好。

program_type = ProgramType.objects.get(pk=1)   
programs = ProgramPage.objects.live().public().filter(program_types__in=[program_type])

这里是models.py的完整代码:

# program/models.py

from django import forms
from django.db import models

from modelcluster.fields import ParentalManyToManyField

from wagtail.core.models import Page
from wagtail.core.fields import RichTextField
from wagtail.admin.edit_handlers import FieldPanel
from wagtail.snippets.models import register_snippet


@register_snippet
class ProgramType(models.Model):
    name = models.CharField(max_length=255)

    panels = [
        FieldPanel('name'),
    ]

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "Program types"


class ProgramPage(Page):
    description = RichTextField(blank=True)
    program_types = ParentalManyToManyField("program.ProgramType", blank=True)

    content_panels = Page.content_panels + [
        FieldPanel('description'),
        FieldPanel('program_types', widget=forms.CheckboxSelectMultiple),
    ]


class IndexProgram(Page):
    program_type = ProgramType.objects.get(pk=1)   
    programs = ProgramPage.objects.live().public().filter(program_types__in=[program_type])

在“makemigrations”或“runserver”之后出现错误:

raise AppRegistryNotReady("Models aren't loaded yet.")

django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

All pages have a get_context method that is called whenever the template is rendered and returns a dictionary of variables to bind into the template.

class IndexProgram(Page):    
    def get_context(self, request):
        context = super().get_context(request)
        program_type = ProgramType.objects.get(pk=1)
        context['programs'] = ProgramPage.objects.live().public().filter(program_types__in=[program_type])