我有抽象模型:
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()移动到abstact类,所以它在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]具有相关对象时才有效,但这并不总是正确的。
答案 0 :(得分:0)
正如我从这段代码中看到的,所有模型都是相同的但命名不同。
为什么不为Modeling创建基类并为每个模型创建实例?
关于all_obj(self),只需将其设为通用(全局)
即可答案 1 :(得分: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