2

假设我有以下模型:

class SomeSuperClass(models.Model):
    ...

class SomeSubClassA(SomeSuperClass)
    ...

class SomeSubClassB(SomeSuperClass)
    ...

class SomeConnector(models.Model):
    reference = models.ForeignKey(SomeSuperClass, on_delete=models.CASCADE)
    ...

现在我想要的是在迭代对象时,SomeConnector我总是想立即拥有相应子类的对象,而不是超类的对象。例如

for sc in SomeConnector.objects.all():

    # somehow get the correct subclass of this `reference` field here,
    # assuming it to be callable under sc.reference_correct_subclass:
    print(sc.reference_correct_subclass.__class__.__name__)

可以产生例如:

'SomeSubClassA'
'SomeSubClassB'
'SomeSubClassA'
'SomeSubClassA'

但是永远不应该使用超类的对象。

我知道django-model-utils,我可以通过直接查询超类来做类似的事情,如下所示:

SomeSuperClass.objects_inheritance.select_subclasses()

附在哪里。objects_inheritance_ 但是,当超类用作我想用于查询的另一个类中的外键时,我还无法弄清楚如何重现这一点。InheritanceManagerSomeSuperClass

4

1 回答 1

0

我可以通过在这个线程ForeignKey中找到的一个额外的子类对字段进行子类化来使其工作。ForwardManyToOneDescriptor

这个子类化的代码是这样的:

from django.db.models.fields.related_descriptors import ForwardManyToOneDescriptor

class InheritanceForwardManyToOneDescriptor(ForwardManyToOneDescriptor):
    def get_queryset(self, **hints):
        return self.field.remote_field.model.objects_inheritance.db_manager(hints=hints).select_subclasses()


class InheritanceForeignKey(models.ForeignKey):
    forward_related_accessor_class = InheritanceForwardManyToOneDescriptor

并在我的代码示例中使用它,然后它将像这样集成:

class SomeConnector(models.Model):
    reference = InheritanceForeignKey(SomeSuperClass, on_delete=models.CASCADE)

于 2020-10-01T21:42:50.873 回答