JobFinancialInfo 上的 @property 将返回第二个模型中的所有对象,该模型的 ID 为 self.id 的 JobFinancialInfo。
因为它是一个OneToOneField,所以最多个这样的对象。事实上,OneToOneField 本质上是ForeignKey,即unique=True,因此这意味着不能有两个模型引用同一个对象。
如果你创建一个OneToOneField,Django 将自动反向构造一个关系,这意味着如果另一个模型名为OtherModel,你可以访问OtherModel指的是 JobFinancialInfo 对象:
<i>myjobfinancialinfo</i>.<b>othermodel</b>
如果没有这样的元素,这将引发OtherModel.DoesNotExist 异常。
所以你可以尝试通过以下方式找到它:
try:
myjobfinancialinfo.othermodel
except OtherModel.DoesNotExist:
# … do something …
pass
您可以使用与ForeignKey [Django-doc] 的多对一 关系,在这种情况下,多个OtherModels 可以链接到相同 JobFinancialInfo。在这种情况下,您可以通过以下方式检索项目:
<i>myjobfinancialinfo</i>.<b>othermodel_set</b>.all()
这可以是包含零个、一个或多个元素的QuerySet。
如果您不想使用<i>othermodel</i> 或<i>othermodel</i>_set,可以更改related_name=… parameter [Django-doc] 以指定另一个名称。
例如,如果OtherModel 看起来像:
class OtherModel(models.Model):
financial_info = models.ForeignKey(
JobFinancialInfo,
related_name='othermodels'
)
然后你访问相关的对象:
<i>myjobfinancialinfo</i>.<b>othermodels</b>.all()