django-polymorphic
django-polymorphic copied to clipboard
Foreign key resolves to parent class when using abstract models
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.
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.
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.