Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy set default value of one column to that of another column

Tags:

I am trying to write a class for substances which has a name filed (for the name, as commonly used in the lab) and another column for the long name (in case the name is actually incomplete). Is there some wy to tell the class to just copy the value of the name field to the long name field in case a long name is not specified?

I tried something like this:

class Substance(Base):     __tablename__ = "substances"     id = Column(Integer, primary_key=True)     code = Column(String, unique=True)     name = Column(String, unique=True)     long_name = Column(String, unique=True, default=name) 

But this fails, since name is undefined. Is there anything else I could do?

like image 347
TheChymera Avatar asked Apr 12 '16 16:04

TheChymera


2 Answers

You can create context-sensitive default function

def mydefault(context):     return context.get_current_parameters()['name']  class Substance(Base):     __tablename__ = "substances"     id = Column(Integer, primary_key=True)     code = Column(String, unique=True)     name = Column(String, unique=True)     long_name = Column(String, unique=True, default=mydefault) 
like image 136
r-m-n Avatar answered Sep 21 '22 02:09

r-m-n


In addition to r-m-n's answer if you have more than one column that defaults to value of another one, you can write a helper function to avoid writing many default functions.

def same_as(column_name):     def default_function(context):         return context.current_parameters.get(column_name)     return default_function  # or as a one-liner same_as = lambda col: lambda ctx: ctx.current_parameters.get(col)  class Substance(Base):     __tablename__ = "substances"     id = Column(Integer, primary_key=True)     name = Column(String, unique=True)     long_name = Column(String, unique=True, default=same_as('name'))     created = Column(DateTime, default=datetime.now)     edited = Column(DateTime, default=same_as('created')) 
like image 23
vil Avatar answered Sep 21 '22 02:09

vil