0

如果我有一个带有 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 分支的所有其他字段。主要是因为如果我有另一个为空的关系对象,空白=真,这会变得更加混乱。

4

1 回答 1

1

我会尽量避免两次定义其他字段。

def json(self):
    out = {
    'id_number': self.id,
    'common_name': self.common_name,
    #....all the other fields
    }
    if self.campus:
        out['campus'] = self.campus.json()
    return out

请注意,此方法和您的原始方法返回 python 字典,而不是 JSON 编码的字符串。

于 2013-07-14T21:57:05.110 回答