ikhsanudinhakim
ikhsanudinhakim

Reputation: 1634

Elegant way to return json field if field is null in Python

I've a dumb question about my flask REST API. If i have a user model with a lot of information and i want to return it as json. But some of the information is still don't have any value (NULL). What's the elegant way to return it as a empty string or another default value instead of returning it as null.

Something like this:

{ 
  'username': 'foo',
  'fullname' : ''
}

instead of this:

{ 
  'username': 'foo',
  'fullname' : null
}

This is my function:

def json(self):
        return {
            'username': self.phone,
            'fullname': self.fullname
        }

This is the user model:

class UserModel(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80))
    password = db.Column(db.String(80))
    fullname = db.Column(db.String(80)) 

Upvotes: 1

Views: 1446

Answers (3)

Sergey Elkin
Sergey Elkin

Reputation: 76

Basically, if you want to override None value in Python, you can use or operator like this:

def json(self):
    return {
        'username': self.phone,
        'fullname': self.fullname or 'some default value'
    }

In case self.fullname has a value, it will be returned. But if it's None, then 'some default value' comes up.

Hope that helps.

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

sqlalchemy.schema.Column class allows specifying default= parameter:

class UserModel(db.Model):
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80))
    password = db.Column(db.String(80))
    fullname = db.Column(db.String(80), default="") 

https://docs.sqlalchemy.org/en/latest/core/metadata.html#sqlalchemy.schema.Column.params.default

Upvotes: 3

SimonF
SimonF

Reputation: 1895

One way is to have conditions in your return dict:

def json(self):
        return {
            'username': self.phone if self.phone else '',
            'fullname': self.fullname if self.fullname else ''
        }

Upvotes: 1

Related Questions