在 Django 中,是否可以为某个超类定义外键,但在查询时返回了子类?

In django, is it possible to have a foreign key defined to some superclass, but having returned the subclass when queried?

假设我有以下模型:

class SomeSuperClass(models.Model):
    ...

class SomeSubClassA(SomeSuperClass)
    ...

class SomeSubClassB(SomeSuperClass)
    ...

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

现在我想要的是在遍历 SomeConnector 的对象时不知何故我总是希望立即拥有相应的子classes 的对象,而不是 super[=31] 的对象=]是的。例如

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'

但是永远不要使用 superclass 的对象。

我知道 django-model-utils,我可以通过直接在 superclass 上查询来做类似的事情,就像这样:

SomeSuperClass.objects_inheritance.select_subclasses()

其中 objects_inheritance 是附加到 SomeSuperClassInheritanceManager。但是,当 superclass 用作我想用于查询的另一个 class 中的外键时,我还不知道如何重现它。

我可以通过将 ForeignKey 字段与我在 this thread.

中找到的额外子类 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)