从两个级别深入的多对一关系中获取对象集

时间:2017-02-21 16:10:53

标签: python django elasticsearch

我有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中执行模型导入:)

1 个答案:

答案 0 :(得分:1)

尝试进行类似

的查询
Model.objects.filter(Make__dealer=kwargs['instance'])