I have a Data Table called “items” with columns “price”, “deal_price”, and “percent_discount”, based on the CRUD app tutorial “Build a News Aggregator”
I only want the user to have to fill out the “price” and “deal_price”, and the “percent_discount” field in the Data Table to be calculated automatically when the row is created or updated.
What would be the best way/place to do this?
Assuming I have understood you correctly …
…you would calculate the percent_discount before you add or update the record. So for example -
pd = float( 100 - ((deal_price / price) * 100) )
row = app_tables.mytable.add(price=price, deal_price =deal_price, percent_discount=pd)
Is that what you mean?
1 Like
Sorry I’m new to to Python, so your answer makes sense to me but how do I apply it in the context of how the News Aggregator is set up with a dictionary?
Here is the server code:
@anvil.server.callable
def add_meal(meal_dict):
app_tables.meals.add_row(
created=datetime.now(),
owner=anvil.users.get_user(),
active=True,
**meal_dict
)
And here is where it is called from the form:
def primary_color_1_click(self, **event_args):
"""This method is called when the button is clicked"""
# Add meal button click
new_meal ={}
if alert(content=mealEdit(item=new_meal),title="Add Meal",
large=True, buttons=[("Save", True),("Cancel", False)]):
anvil.server.call('add_meal', new_meal)
I’m not familiar with the application, but if the dictionary new_meal
contains the data to be added to the table, then I’m assuming it looks something like this (using your original question’s parameters and using made up values for illustration) :
{“deal_price”:5.99, “price”:9.99}
This assumes “percent_discount” has not yet been added as it has not yet been calculated.
So your server function might now look something like this :
@anvil.server.callable
def add_meal(meal_dict):
# Print some debug to confirm meal_dict contains what you think it does.
print("meal_dict = ", meal_dict)
# Assign these vars to make the calculation line a bit more readable.
deal_price = float(meal_dict['deal_price'])
price = float(meal_dict['price'])
# Insert a new key-value into the dictionary
meal_dict['percent_discount'] = float( 100 - ((deal_price / price) * 100) )
app_tables.meals.add_row(
created=datetime.now(),
owner=anvil.users.get_user(),
active=True,
**meal_dict
)
Does that make sense (with the comments)?
2 Likes
Awesome thank you so much! This worked perfectly.
1 Like