In my views.py
class for a ListView I'm trying to add a formula that uses a specific element from an object in the get_context_data()
method. Here is what I've tried.
Models.py
Class MyModel(models.Model):
foo = models.FloatField()
bar = models.FloatField()
views.py
class MyView(generic.ListView):
template_name = "my_item_list.html"
model = MyModel
def get_context_data(self, **kwargs):
obj = MyModel.objects.get(pk=this_object_id)
var_a = obj['foo']
var_b = obj['bar']
result = var_a * var_b
context = {
'result': result,
}
return context
This throws an object does not support indexing
error. I've tried several different methods of accessing the specific object element without luck. I'm not trying to annotate (which is the vast majority of SO Q&A), just use the value from the specified object field.
As a side note, if I pass obj
into the context data I can easily iterate to the element value in the template - so i know that the .get()
method is working correctly - it's just the "simple" math in the view I can't get to work.
I did find this (model_to_dict()
), but it is turning the obj
into a dictionary - I think this could work, but seems much more wordy than I would expect.