Django, add properties to model instances

I've just discovered a great thing on django. Like in javascript, it is possible to add dynamically properties to a model instance, and use them inside a template. This is extremely useful in my opinion because saves us from creating a new dictionary mapping the object properties with the addition of the properties that we want to add.

Here a short example: I have a model WorkingPlace which is related to a model Case in the sense that every Case is relative to an association Person-WorkingPlace. A Case has m2m with a model RiskOk through a CaseRiskOf model which specifies more information, and in particular the field recognized.

Now, in a template I want all the WorkingPlace objects but with the addition of the property recognized. In particular if one of the risks associated with the case associated with the working place has been recognized, I want such properties to be equal to 1, otherwise I want it to be 0.

So here comes the code that can solve such problem, in my view:

working_places = WorkingPlace.objects.all()
for wp in working_places:
  recognized = CaseRiskOf.objects.filter(recognized=True, case__person_working_place__working_place=wp).count()
  if recognized > 0:
    wp.recognized = 1
  else: wp.recognized = 0

The if you cycle through working_places inside a template you can retrieve the property recognized:

{% for wp in working_places %}

  recognized: {{ wp.recognized }}

{% endfor %}

That's all, just a usefull tip.

Comments

post a comment

Sunday 07 October 2012 10:54:53 - gipi
gravatar

This is very strange and new to me but seems correct: normal classes can have runtime defined attribute, the only constraint here is that the class has to have the __dict__ attribute.

Some builtin types (like list) have not defined this attribute and (without subclassing them) it's not possibile to add user defined attribute at runtime.

Look at this http://www.cafepy.com/article/python_attributes_and_methods/ch03s02.html

Bye