[Solved]-Making transient (non-database) attributes in Django model available to template

11👍

The reason why you aren’t seeing these values in your template is that every time you call car.meter_set.all() you get a completely new queryset straight from the database.

Django model instances don’t have identity, so even though the Meter objects in one queryset have the same database values as the ones in another, they do not share any dynamic attributes.

One way to do this would be to cache the Meter objects within each Car, as I show here on a recent question. Then instead of referring to car.meter_set.all() in the view, model and template, you would do car.get_meters() or whatever, and you would get the same set of objects each time, along with your dynamic attributes.

1👍

I tried something similar in my own code and it looks like the problem you’re running into is happening in the read_meter() method and odomoter() view.

The meter and car objects that you’re using to iterate through the QuerySets are falling out of scope, and the changes you make to their attributes is going with them.

When you display meter.difference and meter.changed in the template, Django’s recreating those objects from the DB (and without the unsaved attribute values).

Hope that explanation is clear. Any reason not to save the values to the DB?

Leave a comment