How can I use a non-standard object as a state variable? #470
-
|
I'm not sure if that question makes sense, but here's what's up: 1. Add a page with an on_load event to load data on page load app.add_page(bot, route="/bot/[sl]", on_load=State.get_bot)2—works: Get the associated object and set string variables with its values def get_bot(self):
with pc.session() as session:
slug = self.get_query_params().get("sl", "Missing slug.")
bot: Bot = session.execute(Bot.select.filter(Bot.slug == slug)).first()
if bot:
self.bot_name = bot[0].name
self.bot_personality = bot[0].personality
self.bot_sample = bot[0].sample2—doesn't work: Get the associated object and set a single object variable def get_bot(self):
with pc.session() as session:
slug = self.get_query_params().get("sl", "Missing slug.")
bot: Bot = session.execute(Bot.select.filter(Bot.slug == slug)).first()
self.bot = bot[0]If I do this, then I'll get an error if I try to access bot values like What am I doing wrong? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
|
I think you need to define a custom vars Bot: |
Beta Was this translation helpful? Give feedback.
-
|
Okay, here's the answer: 1. Create a custom var using either pc.Model or pc.Base class Bot(pc.Model, table=True):
slug: str
name: str
personality: str
sample: str2. Within your state class, create an instance of the custom var class and be sure to instantiate it class State(pc.State):
current_bot: Bot = Bot(
slug="",
name="",
personality="",
sample="",
)3. Create a function to populate the variable on page load def get_bot(self):
with pc.session() as session:
slug = self.get_query_params().get("sl", "Missing slug.")
bot: Bot = session.execute(Bot.select.filter(Bot.slug == slug)).first()
if bot:
self.current_bot = bot[0]4. Add the function to your definition for the page app.add_page(bot, route="/bot/[sl]", on_load=State.get_bot)5. Use the variable within your page pc.heading(State.current_bot.sample)WARNING: If you have an attribute called "name," it will not work. If you use this you will instead just get the name of the variable, e.g. "current_bot" in this case. I'm not sure if there's a way around this apart from just not using that attribute name, which is unfortunate. |
Beta Was this translation helpful? Give feedback.
Okay, here's the answer:
1. Create a custom var using either pc.Model or pc.Base
2. Within your state class, create an instance of the custom var class and be sure to instantiate it
3. Create a function to populate the variable on page load