如果我有一个带有 ForeignKey Campus 对象的 Building 对象,我将如何修改 Building 的 JSON 方法,使其看起来不像这样丑陋:
def json(self):
if self.campus:
return {
'id_number': self.id,
'campus': self.campus.json(),
'common_name': self.common_name,
#....all the other fields
}
else:
return {
'id_number': self.id,
'common_name': self.common_name,
#....all the other fields
}
上面的代码有效。我想知道是否有一种方法可以格式化 if 语句,以便我可以重新定位它而不必列出两个 if 分支的所有其他字段。主要是因为如果我有另一个为空的关系对象,空白=真,这会变得更加混乱。