I\'m having trouble accessing a parent class member variable id
from the child class.
class BaseModel:
id = db.Column(db.Integer, primary_key=Tr
A class definition's body is its own scope and the names introduced will form the class' namespace. The problem (in your original question) with your model definition is that the name id
has not been assigned to in the body of the class User
, so the joins in the relationship
definition refer to the builtin function id(). You also cannot use BaseModel.id
as shown in this question, because the Declarative metaclass will create a copy of it to User, so it does not refer to the same column.
The solution is to use lazy evaluation: either pass a callable, or a Python-evaluable string as the join:
followed = db.relationship(
'User',
secondary=followers,
primaryjoin='followers.c.follower_id == User.id', # Note: the joins are
secondaryjoin='followers.c.followed_id == User.id', # passed as strings
backref=db.backref('followers', lazy='dynamic'),
lazy='dynamic')
This works because the inter-mapper relationships of mappers are configured after the mapped classes have been declared and are used for the first time, unless explicitly configured using configure_mappers().
Note that you cannot use plain id
in the evaluable string either, but must instead refer to it using the User
class, since it is evaluated later in a completely different scope from that of the class body, including names from the Declarative class registry, and metadata.
The last error is the result of code such as
User.query.get(some_id)
The assignment of BaseModel.id
to another name – such as testing
– in the class body results in your model having a composite primary key, formed from 2 integer columns, so Query.get() expected to receive a 2-tuple of integers, not just one integer.