django-polymorphic icon indicating copy to clipboard operation
django-polymorphic copied to clipboard

How to have attribute accessor resolve to final polymorphic child class

Open sam-ghosh opened this issue 4 years ago • 4 comments

I am using django-polymorphic

I have a

class Base(PolymorphicModel):
    # some fields

class Child(Base):
    # some field


class Foo(models.Model):
	fk = models.ForeignKey(Base, null=True, on_delete=models.SET_NULL)

And I use them as

child = Child.objects.create(..)
foo = Foo.objects.create(fk=child, ...)

later when I want to access

foo.fk # this gives a Base class obj instead of a child class obj via polymorphism

i want to get foo.fk as the Child object, but I instead get the Base object. I have to do :

Child.objects.get(id=foo.fk.id)

Is there a way to get the attribute accessor foo.fk resolve to Child class directly?

sam-ghosh avatar Jan 16 '21 15:01 sam-ghosh

Did you make any progress on this? I'm also running into this problem.

joshua-davis-rose avatar Apr 04 '21 13:04 joshua-davis-rose

No real solution I'm just using Basemodel.objects.get(id=id)

sam-ghosh avatar Apr 04 '21 13:04 sam-ghosh

Why is no one responding to this issue

ZeroCoolHacker avatar Jul 06 '21 11:07 ZeroCoolHacker

I think this scenario is the reason that there's a get_real_instance method on PolymorphicModel. The manager for Foo is ordinary Django, so an extra query has to be incurred, here.

If the code in question can predict what the polymorphic_ctype will be ahead of time, the extra query could potentially be avoided.

johncronan avatar May 09 '22 23:05 johncronan