In my application I would like all tables save and read data by Company Id. All tables have FK to Company Id. I've override Login and Registration views to Login by providing Company, User and Password. Company Id is shown in "g.user.cia_id_fk" after user logged-in. cia_id_fk has been added to "ab_user" enter image description here My approach is to "default" cia_id_fk to "g.user.cia_id_fk" in the Model. I am following "extendsecurity2" example (https://github.com/dpgaspar/Flask-AppBuilder/blob/master/examples/extendsecurity2/app/models.py) where "Contact" model Created_by column is defaulted to "g.user.id"
model.py
class Company(Model):
__tablename__ = "company"
id = Column(Integer, primary_key=True)
code = Column(String(15), unique=True, nullable=False)
name = Column(String(60), unique=False, nullable=False)
class AlpUser(User):
__tablename__ = 'ab_user'
cia_id_fk = Column(Integer, ForeignKey("company.id"), nullable=False)
class Status(Model):
__tablename__ = "WorkItemStatus"
id = Column(Integer, primary_key=True)
status = Column(String(30), nullable=False)
@declared_attr
def cia_id_fk(cls):
return Column(
Integer, ForeignKey("company.id"), default=cls.get_cia_id, nullable=False
)
@declared_attr
def cia_id(cls):
return relationship(
"Company",
primaryjoin="%s.cia_id_fk == Company.id" % cls.__name__,
enable_typechecks=False,
)
@classmethod
def get_cia_id(cls):
try:
return g.user.cia_id
except Exception:
return None
When try to add a record in "status" I get this error: Note that field "cia_id_fk" is not shown in the form.
integrity error: (sqlite3.IntegrityError) NOT NULL constraint failed: status.cia_id_fk
[SQL: INSERT INTO "status" (status, cia_id_fk) VALUES (?, ?)]
[parameters: ('pending', None)]
This indicate that "default" did not work. I'd tried may variations but not luck. Note that Example mention above works fine but design is different and I would like something simpler.
Any other approach (like set in pre form) is welcome.
Thanks in advance for any help