Bill Armstrong
Bill Armstrong

Reputation: 1777

Django ListView settting variable to model instance element

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.

Upvotes: 0

Views: 539

Answers (1)

user8060120
user8060120

Reputation:

you should use attribute, object is the instance of model class not dict

    var_a = obj.foo
    var_b = obj.bar
    result = var_a * var_b

and best is create property in the declare of the model:

Class MyModel(models.Model):
    foo = models.FloatField()
    bar = models.FloatField()

    @property
    def multiply_fb(self):
        return self.foo * self.bar

and in the view:

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)
        context = {
            'result': obj.multiply_fb,
        }
        return context

Upvotes: 2

Related Questions