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

Foreign key resolves to parent class when using abstract models

Open mcovalt opened this issue 5 years ago • 2 comments

Problem Foreign key lookups don't upcast to their actual type when a parent polymorphic model inherits from an abstract base class. This is inconsistent with the behavior described here.

Example:

from django.db import models
from polymorphic.models import PolymorphicModel

class CommonInfo(models.Model):
    class Meta:
        abstract = True

class Parent(CommonInfo, PolymorphicModel):
    fk = models.ForeignKey("self", on_delete=models.CASCADE, null=True)

class Child(Parent):
     field = models.CharField(max_length=10)


related_obj = Child.objects.create(field="related child")
obj = Child.objects.create(fk=related_obj, field="child")
obj.refresh_from_db()
type(obj.related_obj) == Child    # False
type(obj.related_obj) == Parent   # True

A PR with a failing test has been made: #438

Resolution Adding base_manager_name = "objects" to CommonInfo.Meta resolves the issue.

mcovalt avatar May 20 '20 20:05 mcovalt

Had the same issue. Moving the abstract class right of the PolymorphicModel in the class definition also resolves it. So PolymorphicModel should be kept as first for the method resolution order.

mehmetakyuz avatar Aug 20 '20 12:08 mehmetakyuz

Note: this wasn't an issue for django-polymorphic<2, so if you're migrating you need to make sure to adjust inheritance order like @mehmetakyuz noted above.

trybik avatar Feb 05 '21 10:02 trybik