简体   繁体   English

在不知道Django中模型名称的情况下获取所有相关对象

[英]Get all related objects without knowing model name in Django

I have abstract model: 我有抽象模型:

class CModel(CParent):

    class Meta:
        abstract = True

And have two models based on this abstract model: 并基于此抽象模型有两个模型:

class Model1(CModel):
    pass

class Model1_A(models.Model):
    model = models.ForeignKey(Model1, related_name="a")

class Model1_A_B(models.Model):
    model = models.ForeignKey(Model1_A, related_name="b")

and second: 第二:

class Model2(CModel):
    def all_obj(self):
        ...
        list = Model2_A_B.objects.filter(model__model__pk=self.pk).all()
        ...

class Model2_A(models.Model):
    model = models.ForeignKey(Model2, related_name="a")

class Model2_A_B(models.Model):
    model = models.ForeignKey(Model2_A, related_name="b")

And now I would like to move function all_obj() to abstact class, so it will be avalible in Model1 too, but for Model1 i need something like this: 现在我想将函数all_obj()移到abstact类,因此它也将在Model1中可用,但是对于Model1,我需要这样的东西:

list = Model1_A_B.objects.filter(model__model__pk=self.pk).all()

How can i make all_obj() work for any model name? 如何使all_obj()适用于任何模型名称?

I came up with something like this: 我想到了这样的东西:

list = eval(self.a.all()[:1][0].b.all()[:1][0].__class__.__name__).objects.filter(model__model__pk=self.pk)

But i don't think that this is right way to do. 但是我不认为这是正确的方法。 And there is problem with that, it is work only if self.a.all()[:1][0] have related objects but this is not always true. 并且有一个问题,只有在self.a.all()[:1] [0]具有相关对象的情况下才起作用,但这并不总是正确的。

As i can see from this code all your models are the same but with different naming. 正如我从这段代码中看到的那样,您的所有模型都是相同的,但命名不同。

Why not create base class for Modeling and create instance to each model? 为什么不为Modeling创建基类并为每个模型创建实例?

Regarding the all_obj(self) just make it generic(global) 关于all_obj(self)仅使其通用(global)

class CModel(models.Model):
    _related_model = None

   def all_obj(self):
       if self._related_model is None:
           # you could also return None or an EmptyQueryset or whatever
           raise NotImplementedError("CModel subclasses must define '_related_model'")

       # you don't need the `.all()` after a `.filter()`
       return self._related_model.objects.filter(model__model__pk=self.pk)

   # your code here

class Model1(CModel):
    # note that you'll have to define Model_1_A_B before 
    _related_model = Model_1_A_B

    # etc

class Model2(CModel):
    # note that you'll have to define Model_2_A_B before 
    _related_model = Model_2_A_B

    # etc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM