Reputation: 886
How do I get attr to be the name of the column being checked and value the value of the column being checked?
models.py
class Dates(db.Model):
username=db.Column(db.String, primary_key=True)
apples = db.Column(db.DateTime)
oranges = db.Column(db.DateTime)
milk = db.Column(db.DateTime)
bananas = db.Column(db.DateTime)
beans = db.Column(db.DateTime)
def is_expired(self, date)
#I want attr to equal the column it is coming from
#example if I typed Dates.apples.is_expired('2017-01-01')
#I want attr to equal 'apples', that way Rules.rule brings back
# the rule # associated with apples
#I want value to be the date from Dates.apples
a=Rules.query.filter_by(name=attr).first()
if a.rule=='1':
value=datetime.datetime.strptime(value, '%Y-%m-%d')
date=datetime.datetime.strptime(date, '%Y-%m-%d')
for i in range(36):
value=add_one_month(value)
if date>value:
return True
else:
return False
elif a.rule=='2':
value=datetime.datetime.strptime(value, '%Y-%m-%d')
date=datetime.datetime.strptime(date, '%Y-%m-%d')
for i in range(12):
value=add_one_month(value)
if date>value:
return True
else:
return False
def __repr__(self): # pragma: no cover
return '<Mobility %r>' % (self.username)
class Rules(db.model)
rule=db.Column(db.Integer, primary_key=True)
name=db.Column(db.String(45))
def __repr__(self): # pragma: no cover
return '<Mobility %r>' % (self.name)
Example of a call in another function:
user=Dates.query.filter_by(username='bob').first()
user.apples='2017-02-11'
if user.apples.is_expired('2017-04-12'):
color=red
In this case attr='apples', value='2017=02-11'
Upvotes: 1
Views: 150
Reputation: 16182
If you want to have attr
inside the function, you should pass it as a parameter.
This is not about SQLAlchemy actually - python object don't work the way you try to use it here: object.attr.method()
is not a valid way to call object
's method.
Instead you need something like user.is_expired('apples', '2017-04-12')
. Inside the method you can get the field value as getattr(self, attr_name)
, assuming that you change the method signature to def is_expired(self, attr_name, date)
.
Upvotes: 1