Skip to content

select_related() from a plain model with a ForeignKey to a polymorphic model #244

@Bartvds

Description

@Bartvds

If you have a regular model that has a ForeignKey to a polymorphic model, and then use select_related() from the regular model''s manager/queryset to select the related polymorphic instances we only get these downcasted as the base class of the polymorphic model.

Illustration:

class ParentModel(PolymorphicModel):
    pass

class ChildModel(ParentModel):
    # some fields etc
    pass   

class PlainModel(models.Model):
    relation = models.ForeignKey(ParentModel)


# if we let it do 1+n
for obj in PlainModel.objects.all():
    # these obj.relation values will have their proper sub type
    print(type(obj.relation))

# if we select_related()
for obj in PlainModel.objects.select_related('relation'):
    # these obj.relation values will all be ParentModel's
    print(type(obj.relation))

My quess is the PlainModel's manager is not aware it has to apply the polymorphic magic? Is this expected behaviour? I see the note on select_related() here http://django-polymorphic.readthedocs.io/en/stable/advanced.html but I think it doesn't apply.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions