Egorrko
Egorrko

Reputation: 63

Get sqlAlchemy field name

I have sqlAlchemy model with table like that:

Base = declarative_base()
class User(Base):
__tablename__ = 'user'
uid = Column('id', Integer, primary_key=True)
name = Column('name', String(255), nullable=False)
surname = Column('surname', String(255), nullable=False)

I want to create method "user_errors" that will be return dictionary of incorrect fields

errors = {field_name : field_content}

But i don't know how get field_name in code.

I want use it something like this:

def user_errors(user):
    errors = {}
    if is_error(user.name):
        errors[user.name.__name__] = user.name
    ...
    return errors

Upvotes: 1

Views: 564

Answers (1)

Are you going to implement it as method of the User class, aren't you?

If it's so, the code below should work for you:

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

def is_error(name):
    if name != "Guido Van Rossum":
        return True
    return False


Base = declarative_base()
class User(Base):
    __tablename__ = 'user'
    uid = Column('id', Integer, primary_key=True)
    name = Column('name', String(255), nullable=False)
    surname = Column('surname', String(255), nullable=False)
    
    def user_errors(self):
        errors = {}
        if is_error(self.name):
            errors["user_name"] = self.name
        # do some stuff 
        return errors

Output:

>>> user = User()
>>> user.name = 'test'
>>> user.user_errors()
 {'user_name': 'test'}

If you want to create a separate function though, your version is about right:

user = User()
user.name = 'test'

def user_errors(user):
   errors = {}
   if is_error(user.name):
        errors["user_name"] = user.name
        # do some stuff 
        return errors

user_errors(user)

Output:{'user_name': 'test'}

As I see, you don't need to use some magic parameters to set a key name for error dict, as you already defined that you're checking a user name, anyway, if you want to unify the error check and iterate all the user class parameters, try to use sth like this:

def user_errors(user):
    errors = {}
    for col_name in user.__table__.columns.keys():
        col_value = user.__getattribute__(col_name)
        if is_error(col_value):
            errors[col_name] = col_value
        # do some stuff 
    return errors

# to get this stuff working you should define ALL class attributes, otherwise - get exeption
user = User()
user.id = 1
user.name = 'test'
user.surname = 'test'

user_errors(user)
Output: {'id': 1, 'name': 'test', 'surname': 'test'}

Hope it'll help you

Useful links: https://www.tutorialsteacher.com/python/magic-methods-in-python

Upvotes: 1

Related Questions