Django, add properties to model instances
You can also be interested in:
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.
Your Smartwatch Loves Tasker!

Your Smartwatch Loves Tasker!
Featured

Django admin and bootstrap 5
Bootstrap 5 has come, currently in beta release, and seems already very stable.
So the question is: are you looking for ...

About code optimization, learn from exercises
Let's see an example of exercise you can face during a job interview, and let's use it to understand some ...

Notes on the Pearson correlation coefficient
The Pearson correlation coefficient is a measure of the linear correlation between two variables X and Y. It has a ...
Archive
- 2021
- 2020
- 2019
- 2018
- 2017
- Nov
- Oct
- Aug
- Jun
- Mar
- Feb
- 2016
- Oct
- Jun
- May
- Apr
- Mar
- Feb
- Jan
- 2015
- Nov
- Oct
- Aug
- Apr
- Mar
- Feb
- Jan
- 2014
- Sep
- Jul
- May
- Apr
- Mar
- Feb
- Jan
- 2013
- Nov
- Oct
- Sep
- Aug
- Jul
- Jun
- May
- Apr
- Mar
- Feb
- Jan
- 2012
- Dec
- Nov
- Oct
- Aug
- Jul
- Jun
- May
- Apr
- Jan
- 2011
- Dec
- Nov
- Oct
- Sep
- Aug
- Jul
- Jun
- May