jazzband / django-polymorphic

Improved Django model inheritance with automatic downcasting
https://django-polymorphic.readthedocs.io
Other
1.63k stars 280 forks source link

How to have attribute accessor resolve to final polymorphic child class #477

Open sam-ghosh opened 3 years ago

sam-ghosh commented 3 years ago

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?

joshua-davis-rose commented 3 years ago

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

sam-ghosh commented 3 years ago

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

ZeroCoolHacker commented 3 years ago

Why is no one responding to this issue

johncronan commented 2 years ago

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.