[Answer]-If statement in Django JSON method


I would try to avoid defining the other fields twice.

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

Note that this method and your original method return a python dict, not a JSON encoded string.

Leave a comment