Q:

Reverse access to OneToOne field in an abstract model

Suppose I have the following database structure:
class Asset(models.Model):
    # ...

class AbstractBuilding(models.Model):
    asset = models.OneToOneField(Asset, on_delete=models.CASCADE, primary_key=True)
    # ...

    class Meta:
        abstract = True

class Office(AbstractBuilding):
    # ...

class Lab(AbstractBuilding):
    # ...

class PowerPlant(AbstractBuilding):
    # ...

If I have an Office object, it's easy to get the corresponding Asset through the one-to-one field (e.g. office_object.asset returns an Asset). However, suppose I have a Asset instead. How can I get the corresponding Office (or Lab or PowerPlant) from the Asset object?

A:

# You have an instance of Asset e.g.
asset = Asset.objects.first()

office = getattr(asset, "office") # gives you related office if it is related to office

lab = getattr(asset, "lab") # gives you related lab if it is related to lab

power_plant = getattr(asset, "powerplant") # gives you related powerplant if it is related to powerplant

