假设我具有以下数据库结构:
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
(或PowerPlant
或Asset
)?
答案 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