[英]Django get plain value of Foreign Key
我有以下 model:
def MyModel(models.Model):
other = models.ForeignKey(OtherModel, db_column='other', on_delete=models.DO_NOTHING, db_constraint=False, blank=True, null=True)
問題是 model OtherModel
的other
字段中的值(這是一個字符串值)可能不能在MyModel
中,所以當我這樣做時,例如:
inst = MyModel.objects.first() # Gets any (with an "invalid" key in other)
inst.other
它拋出:
others.models.OtherModel.DoesNotExist:OtherModel 匹配查詢不存在。
我希望,如果它不存在,請獲取other
字段的普通值。 我怎么能做到這一點?
任何形式的幫助將非常感激
您可以將邏輯封裝在屬性(或方法)中:
def MyModel(models.Model):
other = models.ForeignKey(
OtherModel,
db_column='other',
on_delete=models.DO_NOTHING,
db_constraint=False,
blank=True,
null=True
)
@property
def other_or_value(self):
try:
return self.other
except OtherModel.DoesNotExist:
return self.other_id
然后使用:
mymodelobject.other_or_value
但是,我不確定這是一個好主意。 現在該方法可以返回兩種類型的對象,通常這會使結果處理更加復雜。 這也意味着數據庫也是如此:它不再能保證參照完整性。 雖然關於引用不存在的 object 的錯誤很煩人,但忽略這些錯誤通常會更糟。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.