Reputation: 6968
I am a self-taught amateur ever trying to understand fundamentals of Python, Django and programming in general. I'm looking to understand an issue I was having.
So I have this class
class ContractsView(InventoryView):
template_name = "contracts.html"
page = "Contracts"
primary_table, secondary_table = build_contracts_tables(**{"commodity": None})
and it uses the following function:
def build_contracts_tables(**kwargs):
print('fire')
primary_table_query = Purchase.inventory.current_contracts_totals(**kwargs)
primary_table_fields = ("total_meats", "total_value", "meat_cost")
primary_table_html = build_table([primary_table_query,], *primary_table_fields) if primary_table_query else err_str
secondary_table_query = Purchase.inventory.current_contracts(**kwargs)
secondary_table_fields = ("invoice", "supplier", "variety", "meats", "value", "meat_cost", "ship_date")
secondary_table_html = build_table(secondary_table_query, *secondary_table_fields) if secondary_table_query else err_str
return primary_table_html, secondary_table_html
Somehow, the view is sending something to the template, as it does render some data. However, the data doesn't update right away (it eventually does), meaning I will refresh it after changes to the database, but old data will persist. Additionally, I don't ever see my print
appear in the console.
However, when I convert the class variables into functions, it works just fine:
class ContractsView(InventoryView):
template_name = "contracts.html"
page = "Contracts"
def primary_table(self):
x,y = build_contracts_tables(**{"commodity": None})
return x
def secondary_table(self):
x, y = build_contracts_tables(**{"commodity": None})
return y
Could someone help me understand the rule I am breaking in my original attempt?
Upvotes: 1
Views: 107
Reputation: 309099
You shouldn't set primary_table
and secondary_table
as class variables, because they will be calculated once when the module is loaded.
As you have already worked out, the correct approach is to use methods. This way, the method runs when the view runs, so you get the up to date value.
Upvotes: 1