Django, add properties to model instances

django programming tips

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.

Subscribe to abidibo.net!

If you want to stay up to date with new contents published on this blog, then just enter your email address, and you will receive blog updates! You can set you preferences and decide to receive emails only when articles are posted regarding a precise topic.

I promise, you'll never receive spam or advertising of any kind from this subscription, just content updates.

Subscribe to this blog

Comments are welcome!

blog comments powered by Disqus

Your Smartwatch Loves Tasker!

Your Smartwatch Loves Tasker!

Now available for purchase!