我有3个模型,我想在给定第一个模型的情况下从第3个模型中获取所有相关对象的集合。
例如:
Clas Dealer(models.Model):
..
class Make(models.Model):
dealer = models.ForeignKey(Dealer)
..
Class Modell(models.Model):
Make = models.ForeignKey(Make)
..
我将如何获得Modell
所有相关的Dealer?
对象。经销商对象将以kwargs['instance']
修改
我无法使用.objects.filter(..)
修改2
from django.apps import AppConfig
from django.db import models
class CarConfig(AppConfig):
name = 'cars'
verbose_name = 'cars'
def ready(self):
from cars.models import Car, Make, Modell
models.signals.post_save.connect(CarConfig.reindex_related_carmodels, sender=Dealer, weak=False,
dispatch_uid="reindex_related_carmodels")
@staticmethod
def reindex_related_carmodels(sender, **kwargs):
from cars.search_indexes import ModelIndex
models = Modell.objects.all()
...
我得到的错误是:global name 'Modell' is not defined
编辑3 如果我尝试在准备之外导入任何模型,我会得到:
File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 124, in check_apps_ready
web_1 | raise AppRegistryNotReady("Apps aren't loaded yet.")
web_1 | django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
编辑4 解决方案是在@staticmethod中执行模型导入:)
答案 0 :(得分:1)
尝试进行类似
的查询Model.objects.filter(Make__dealer=kwargs['instance'])