【问题标题】:Reverse access to OneToOne field in an abstract model反向访问抽象模型中的 OneToOne 字段
【发布时间】:2019-12-10 06:28:01
【问题描述】:

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

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。如何从Asset 对象中获取对应的Office(或LabPowerPlant)?

【问题讨论】:

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


【解决方案1】:
# 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

【讨论】:

  • 如果getattr无法获取指定的相关对象,您可能需要添加捕获django.core.exceptions.ObjectDoesNotExist的示例。
  • 或者更好:office = getattr(asset, Office.__name__.lower())。这避免了必须摆弄字符串。
猜你喜欢
  • 2012-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-05
  • 2018-09-08
  • 2016-06-10
  • 2015-03-16
相关资源
最近更新 更多