Django ошибка: «Модели еще не загружены». - PullRequest
0 голосов
/ 07 мая 2020

Я вносил изменения в свои модели и добавлял новые (много раз). Но теперь, когда я запустил python3 manage.py makemigrations, я внезапно получил эту ошибку: django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

Я удалил все миграции и файл базы данных sqlite, чтобы начать с нуля, но я снова получаю ту же ошибку. Все мои модели зарегистрированы в admin.py.

Я использую Django 2.0.3.

Кто-нибудь может мне с этим помочь?

Вот полный трассировка:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute
    django.setup()
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate
    app_config.import_models()
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/mnt/c/git/project3/orders/models.py", line 85, in <module>
    class PizzaOrder(models.Model):
  File "/mnt/c/git/project3/orders/models.py", line 90, in PizzaOrder
    p = Pizza.objects.get(pk=pizza_id)
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/query.py", line 394, in get
    clone = self.filter(*args, **kwargs)
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/query.py", line 836, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/query.py", line 854, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1253, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1277, in _add_q
    split_subq=split_subq,
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1153, in build_filter
    lookups, parts, reffed_expression = self.solve_lookup_type(arg)
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1015, in solve_lookup_type
    _, field, _, lookup_parts = self.names_to_path(lookup_splitted, self.get_meta())
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1355, in names_to_path
    if field.is_relation and not field.related_model:
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/utils/functional.py", line 36, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/db/models/fields/related.py", line 94, in related_model
    apps.check_models_ready()
  File "/home/anna/py3_cs50W/lib/python3.6/site-packages/django/apps/registry.py", line 132, in check_models_ready
    raise AppRegistryNotReady("Models aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.

Вот мой полный models.py:

from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
from django.contrib.auth.models import User
from django.conf import settings


LARGE = 'L'
SMALL = 'S'
SIZE_CHOICES = ( (SMALL, 'Small'), (LARGE, 'Large'),)

class Dish(models.Model):
  PIZZA = 'PIZZA'
  SUB = 'SUB'
  PASTASALAD = 'PASTASALAD'
  PLATTER = 'PLATTER'
  TYPE_CHOICES = ( (PIZZA, 'Pizza'), (SUB, 'Sub'), (PASTASALAD, 'PastaSalad'), (PLATTER, 'Platter') )
  name = models.CharField(max_length=64, blank=True) # blank makes name optional
  type = models.CharField(max_length=64, choices=TYPE_CHOICES, blank=True)
  size = models.CharField(max_length=1, choices=SIZE_CHOICES, default=SMALL, blank=True)
  price = models.DecimalField(max_digits=6, decimal_places=2, default=None)


  def __str__(self):
    return f"{self.name} {self.size} - Price: ${self.price}"

class Order(models.Model):
  order_id = models.AutoField(primary_key=True)
  customer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.DO_NOTHING, related_name="active_customer")#can ditch rel name
  time = models.DateTimeField()
  total = models.DecimalField(max_digits=7, decimal_places=2)

  def __str__(self):
    return f"Order {self.order_id}, customer: {self.customer}. Total: ${self.total} - {self.time}"


class PastaSalad(Dish):
  dish = models.OneToOneField(Dish, on_delete=models.CASCADE, related_name="dish_id_pastasalad", parent_link=True)

  def __str__(self):
    return f"{self.name}, price: ${self.price}"


class Topping(models.Model):
  name = models.CharField(max_length=64, primary_key=True)

  def __str__(self):
    return f"{self.name}"

class Pizza(Dish):
  dish = models.OneToOneField(Dish, on_delete=models.CASCADE, related_name="dish_id_pizza", parent_link=True)
  REGULAR = 'REGULAR'
  SICILIAN = 'SICILIAN'
  STYLE_CHOICES = ( (REGULAR, 'Regular'), (SICILIAN, 'Sicilian'),)
  style = models.CharField(max_length=64, choices=STYLE_CHOICES, default=REGULAR)
  topping_count = models.IntegerField(default=0, validators=[MaxValueValidator(5), MinValueValidator(0)])

  def __str__(self):
    return f"{self.size} {self.style} pizza with {self.topping_count} toppings: ${self.price}"


class Sub(Dish):
  dish = models.OneToOneField(Dish, on_delete=models.CASCADE, related_name="dish_id_sub", parent_link=True)

  def __str__(self):
    return f"{self.name}, Size: ${self.szie}, Price: ${self.price}"

class PizzaOrder(models.Model):
  pizza_id = models.ForeignKey(Pizza, related_name="pizza_id", on_delete=models.DO_NOTHING)
  order_id = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="pizza_order_id")
  p = Pizza.objects.get(pk=pizza_id)
  toppings = []
  for i in range (p.topping_count):
    str = "topping_"+(i+1)
    toppings.append(str)
  for t in toppings:
      t = models.ForeignKey(Topping)

  def __str__(self):

    return f"Pizza Order: {self.order_id}, Size & Style: {p.size} {p.style}, Toppings: {p.topping_count}"


class Platter(Dish):
  dish = models.OneToOneField(Dish, on_delete=models.CASCADE, related_name="dish_id_platter", parent_link=True)

  def __str__(self):
    return f"{self.name} price: ${self.price}, size ${self.size}"

class PlatterOrder(models.Model):
  order_id = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="platter_to_order_id")
  platter_id = models.ForeignKey(Platter, related_name="platter_id")


  def __str__(self):
    p = Platter.objects.get(pk=platter_id)
    return f"Platter Order: {self.order_id}, {p.name}, size: {p.size}"

class SubOrder(models.Model):
  sub_id = models.ForeignKey(Sub, related_name="sub_id")
  order_id = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="sub_to_order_id")
  extra_count = models.IntegerField(default=0, validators=[MaxValueValidator(4), MinValueValidator(0)])
  MUSHIES = 'M'
  PEPPERS = 'P'
  ONIONS = 'O'
  XTRCHEESE = 'C'
  EXTRA_CHOICES = ((MUSHIES, 'Mushrooms'), (PEPPERS, 'Peppers'), (ONIONS, 'Onions'), (XTRCHEESE, 'Extra Cheese'),)
  extra_1 = models.CharField(max_length=1, choices=EXTRA_CHOICES, blank=True)
  extra_2 = models.CharField(max_length=1, choices=EXTRA_CHOICES, blank=True)
  extra_3 = models.CharField(max_length=1, choices=EXTRA_CHOICES, blank=True)
  extra_4 = models.CharField(max_length=1, choices=EXTRA_CHOICES, blank=True)

  def __str__(self):
    s = Sub.objects.get(pk=sub_id) # LET'S SEE IF THIS WORKS
    extras = []
    for i in range(extra_count):
      str = "extra_"+i
      extras.append(str)
    return f"Sub Order: {self.order_id}, {s.name}, size: {s.size}. {self.extra_count} Extras: {extras}"

class PastaSaladOrder(models.Model):
  order_id = models.ForeignKey(Order, on_delete=models.CASCADE, related_name="pastasalad_to_order_id")
  pastasalad_id = models.ForeignKey(PastaSalad, related_name="pastasalad_id")


  def __str__(self):
    ps = PastaSalad.objects.get(pk=pastasalad_id) # LET'S SEE IF THIS WORKS
    return f"Pasta/Salad Order: {self.order_id}, {ps.name}"

1 Ответ

0 голосов
/ 07 мая 2020

Ваша проблема находится здесь, в PizzaOrder:

  p = Pizza.objects.get(pk=pizza_id)
  toppings = []
  for i in range (p.topping_count):
    str = "topping_"+(i+1)
    toppings.append(str)
  for t in toppings:
      t = models.ForeignKey(Topping)

Как следует из трассировки, ваша модель не загружена, но вы пытаетесь обратиться к ней с помощью .objects.get(). Я думаю, вы хотите связать Pizzas с PizzaOrder, если это так, вам нужно установить это как ForeignKey (или другое отношение) в модели Pizza. Удаление этого сегмента кода должно сработать (хотя у вас есть некоторые недостающие поля on_delete в ваших ForeignKeys).

Структура ваших моделей кажется довольно сложной, я думаю, вы можете избавиться от моделей food и foodOrder как они, наверное, ничего не добавляют. У вас может быть четыре модели, каждая со своими полями выбора:

Order > Platter > Dish > Topping/Extra

Di sh может иметь поле выбора, которое относится к пицце, пасте и т. Д. c. При необходимости укажите цену и ссылку на начинки / добавки.

...