Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Foreign key resolves to parent class when using abstract models #437

Open
mcovalt opened this issue May 20, 2020 · 2 comments
Open

Foreign key resolves to parent class when using abstract models #437

mcovalt opened this issue May 20, 2020 · 2 comments

Comments

@mcovalt
Copy link

mcovalt commented May 20, 2020

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.

@mehmetakyuz
Copy link

mehmetakyuz commented Aug 20, 2020

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.

@trybik
Copy link

trybik commented Feb 5, 2021

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants