Maximilian Kindshofer
Maximilian Kindshofer

Reputation: 2843

Adding a value to an Object retrieved via a QuerySet

In Django I often call Objects via QuerySets and put them in a dict to give them to a template.

ObjectInstance = Object.objects.get(pk=pk)

ObjectsInstanceDict = {'value1': ObjectInstance.value1,
                       'value2': ObjectInstance.value2,
                       'specialvalue': SomeBusinessLogic(Data_to_aggregate)

Sometimes specialvalue is just a timestamp converted to a string other times there are some analysis done with the data.

Instead of creating a dict I would like to add a special value to the ObjectInstance instead so I don't have to repeat all the existing values and just adding new computed values.

How would I do this?

And please tell me if I made a fundamental mistake I work around here.

Upvotes: 0

Views: 63

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599480

Django model instances are normal Python objects. Like almost any other Python object, you can freely add attributes to them at any time.

object_instance = Object.objects.get(pk=pk)
object_instance.special_value = SomeBusinessLogic(data_to_aggregate)

Upvotes: 3

Related Questions