0

我有抽象模型:

class CModel(CParent):

    class Meta:
        abstract = True

并且有两个基于这个抽象模型的模型:

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")

第二:

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")

现在我想将函数 all_obj() 移动到抽象类,所以它也可以在 Model1 中使用,但是对于 Model1 我需要这样的东西:

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

如何使 all_obj() 适用于任何型号名称?

我想出了这样的事情:

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

但我认为这不是正确的做法。并且存在问题,仅当 self.a.all()[:1][0] 具有相关对象时才有效,但这并不总是正确的。

4

2 回答 2

0
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
于 2013-10-09T07:34:37.327 回答
0

正如我从这段代码中看到的那样,您的所有模型都是相同的,但命名不同。

为什么不为建模创建基类并为每个模型创建实例?

关于 all_obj(self) 只需将其设为 generic(global)

于 2013-10-09T07:08:57.897 回答