反向访问抽象模型中的 OneToOne 字段

Reverse access to OneToOne field in an abstract model

假设我有以下数据库结构:

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):
    # ...

如果我有一个Office对象,很容易通过一对一字段得到对应的Asset(例如office_object.asset returns一个Asset).但是,假设我有一个 Asset 。如何从Asset对象中获取对应的Office(或LabPowerPlant)?

# 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