Skip to content

Add related objects descriptors to related objects on subclasses? #249

@blag

Description

@blag

When subclassing from a PolymorphicModel with a relation to another model, it would be awesome if the related model had reverse related descriptors added to it for all subclasses of the polymorphic model.

This is probably better illustrated with an example:

class Company(models.Model):
    ...

class DeviceModel(PolymorphicModel):
    manufacturer = models.ForeignKey(Company, related_name='device_models')
    ...

class TabletModel(DeviceModel):
    ...

class PhoneModel(DeviceModel):
    ...

All Company objects have a reverse related descriptor to the polymorphic superclass:

apple = Company.objects.get(name='Apple')
apple.device_models.all()  # Returns all device models

but they don't have reverse related descriptors to the subclasses:

apple.tabletmodels_set.all()
apple.phonemodels_set.all()

It would be super cool if the related class (Company) had more reverse related descriptors to access subsets of the polymorphic model, like so:

class Company(models.Model):
    ...

class DeviceModel(PolymorphicModel):
    manufacturer = models.ForeignKey(Company, related_name='%(class)ss')
    ...

class TabletModel(DeviceModel):
    ...

class PhoneModel(DeviceModel):
    ...

apple = Company.objects.get(name='Apple')
apple.devicemodels.all()  # All device models, including objects of subclasses
apple.tabletmodels.all()  # Only device models that are tablets, using the `TabletModel`'s default manager
apple.phonemodels.all()  # Only device models that are phones, using the `PhoneModel`'s default manager

This is would make subclassing a polymorphic model a lot more like subclassing an abstract model from vanilla Django.

If there is a known workaround for this I haven't been able to figure it out. Issue #19 looked close but I didn't get it to work since I need DeviceModel to be a concrete class and I didn't want to have foreign keys to app_company table on all of the app_devicemodel, app_tabletmodel, and app_phonemodel tables. Any help is greatly appreciated.

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