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

0๐Ÿ‘

โœ…

I could get it working by subclasing the ForeignKey field with an additionally sublcassed ForwardManyToOneDescriptor as I found in this thread.

The code for this subclassing would be this:

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

And to use it in my code example, then this would be integrated like this:

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

๐Ÿ‘คsteffres

Leave a comment