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

时间:2019-12-10 06:28:01

标签: django database django-models one-to-one

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

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返回一个Asset)。但是,假设我有一个Asset。如何从Office对象中获取相应的Lab(或PowerPlantAsset)?

1 个答案:

答案 0 :(得分:0)

# 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