Where to define a QuerySet in Django - python

I want to define a queryset. In the shell it is all fine and I can filter the column I want with:
pat1 = Patient.objects.get(pk=1)
pat1.examinationgeometry_set.filter(examination='FIRST')
now I want to define a QuerySet out of it but I don't know where to define it and how. In the Views, Templates, Models? And how do I write it? I know that I have to define it with a function but is there any function from django for it?
Idea behind this queryset is to show all of the results in my database from the first examination. So in my template I have sth like this:
{% if Patient.examinationgeometry_set.filter(examination='FIRST') %}
{% for geo in patient.examinationgeometry_set.all %}
<li> x: {{ geo.x }}<br/>
c: {{ geo.c }} <br/>
b: {{ geo.b}}<br/>
n: {{ geo.n}}<br/>
</li>
{% endfor %}
{% endif %}
I am thankful for every hint!

Querysets should be made in the view, not in the template, given your code, it should be something like this:
view.py:
def my_view:
patients = Patient.objects.all()
context = {"patients": patients}
return render(request, "template_path", context)
template.html:
{% for patient in patients %}
{% for geo in patient.examinationgeometry_set.all %}
{% if geo.examination == 'FIRST' %}
<li>
x: {{ geo.x }}<br/>
c: {{ geo.c }}<br/>
b: {{ geo.b}}<br/>
n: {{ geo.n}}<br/>
</li>
{% endif %}
{% endfor %}
{% endfor %}
A better option is to make a python property for your patient model like this:
class Patient(stuff):
# your model stuff
#property
def first_examinationgeometry_set():
# maybe this should use .get() instead of filter?
return self.examinationgeometry_set.filter(examination="FIRST")
and now call this in the template(same view as first example):
{% for patient in patients %}
{% with geo=patient.first_examinationgeometry_set %}
<li>
x: {{ geo.x }}<br/>
c: {{ geo.c }}<br/>
b: {{ geo.b}}<br/>
n: {{ geo.n}}<br/>
</li>
{% endwith %}
{% endfor %}

Related

Django: Nested Loop In Template

category = ['cat1','cat2','cat3']
inventory = CurrentInventory.objects.all()
for cats in categories
inventorybycat = inventory.filter(category =cats)
setofinventories.append(inventorybycat)
dictofstuff = [zip(setofinventories,categories)]
context = {
'setofinventories':setofinventories
'category':category
'dictofstuff':dictofstuff
}
In views.py above this loop creates a list of objects per each category.
In the template below this loop prints a filtered object list per every item in the category list.
{% for inventory in setofinventories%}
{% for item in inventory %}
{{ item.category }}
{{ item.productName }}
{% endfor %}
{% endfor %}
The only thing I am missing is I do not now how to reference the category in the template. I pass the whole list in context, but {{category{{forloop.counter}}}} is not a valid statement.
I would either like to use zip(category,setofinventories) to pass these two items together,
or create a category model, filter by that model and then I can reference that model by item?
If I zip these items dictofstuff = [zip(setofinventories,categories)]
How do I reference the category in the template?
{% for inventory,categories in dictofstuff %}
{% for inventory in setofinventories%}
{% for item in inventory %}
{{ item.quantity }}
{{ item.productName }}
{% endfor %}
{% endfor %}
{% endfor %}
Returns Error: "Need 2 values to unpack in for loop: got 1."
If i right understand you, you want to print category only one time.
In your case:
{% for inventory in setofinventories%}
{% ifchanged inventory.category %}
{{ inventory.category }}
{% endifchanged %}
{% for item in inventory %}
{{ item.quantity }}
{{ item.productName }}
{% endfor %}
{% endfor %}
i use ifchanged, more here:
https://docs.djangoproject.com/en/4.1/ref/templates/builtins/#ifchanged
in views i zipped this to a *listofstuff. Forgive the nomenclature.
dictofstuff = [zip(categories,setofinventories)]
in template. Again, forgive bad nomenclature. I should go back and rename these but it works.
{% for category in dictofstuff %}
{% for item in category %}
{{item.0}}
{% for stuff in item %}
{% for thing in stuff %}
{{thing.productId}}{{thing.productName}}
{% endfor %}
{% endfor %}
{% endfor %}
{% endfor %}

How can I loop through all the properties of an python object in django templates

I have django template and I get a some object.
I want apply for in cycle for all atributes this object.
{% for point in Object %}
<h1>{{ Object[point] }}</h1>
{% endfor %}
You can't do that in the template.
One solution is to convert your object in a dictionary in the view with object.__dict__ and then iterate over it with:
{% for attr, value in object_dict.items %}
{{ attr }} : {{ value }}
{% endfor %}
As py_dude suggests, you can discard attributes starting with underscores to keep your actual attributes.
{% for k, v in Object.__dict__.items() %}
{% if not k.startswith("_") %}
<h1>{{ v }}</h1>
{% endif %}
{% endfor %}

define flag variable in django template

I'm new in Django and I am trying to search for something in a template if I find it a want to print something, if not I want to print something else.
sth like this:
{% for art in artifacts %}
{% if art.product_component == 'A' %}
<p> something.</p>
{{ found = True }}
{% endif %}
{% endfor %}
{% if not found %}
<p>NA</p>
{% endif %}
I know this is not the right way to do it, but this is just to understand the idea.
how can i do it?
You can write a templatetag for finding product_component == 'A' is exist or not.
your_app_dir/templatetags/product_tag.py
from django import template
from django.template import Library
register = Library()
#register.assignment_tag()
def check_product_component_status(artifacts):
value = [art for art in artifacts if art.product_component == 'A']
if value:
return True
return False
template:
{% for art in artifacts %}
{% if art.product_component == 'A' %}
<p> something.</p>
{% endif %}
{% endfor %}
{% load product_tag %}
{% check_product_component_status artifacts as status %}
{% if not status %}
<p> something.</p>
{% endif %}

Is it possible to pass a dictionary of objects from a view to a template

I am wondering if we can pass a dictionary of objects to a template and loop it in a template.
This is my structure:
{
'Communication': [
[EchoCase: EchoCase object, EchoDescription: EchoDescription object],
[EchoCase: EchoCase object, EchoDescription: EchoDescription object]
],
'escalations': [[EchoCase: EchoCase object, EchoDescription: EchoDescription object],
[EchoCase: EchoCase object, EchoDescription: EchoDescription object]]
}
It is basically a dictionary where for each key, the value is a list of list.
I would like to know if there is a way to loop on this within a django template or if this kind of structure is too complicated,
{% for key, value_list in data %}
<ul>
<li> {{ key }}
<ul>
{% for value in value_list %}
<li>{{ value }}</li>
{% endfor %}
</ul>
</li>
</ul>
{% endfor %}
But it looks like Echo Case and Echo Description are related so you might just want to use related fields and do {{ echocase }} {{ echocase.description }} or something similar
I managed to make it worked using Paul's structure
{% for category, liste in template_dictionnary.items %}
<ul>
<li> {{ category }} </li>
<li> {{ liste}} </li>
{% for val in liste %}
<li>Val: {{ val.0.comment }}</li> <!-- val.0 is an EchoCase, val.1 is an EchoDescription -->
<li>Val: {{ val.1.field }}</li>
{% endfor %}
</li>
</ul>
{% endfor %}
Thank you Paul

'for' loop through form fields and excluding one of the fields with 'if'

The problem I'm struggling with is as follows:
I have:
{% for field in form %}
{{ field }}
{% end for %}
What I want is to put an 'if' statement to exclude a field which .label or whatever is provided. Like:
{% for field in form%}
{% if field == title %}
{% else %}
{{ field }}
{% endif %}
{% endfor %}
Is it possible? I have to many fields to write them one by one and only one or two to exclude.
Thank you for any tips.
BR,
Czlowiekwidmo.
Yes, this should be possible:
{% for field in form %}
{% ifnotequal field.label title %}
{{ field }}
{% endifnotequal %}
{% endfor %}
Django's template tags offer ifequal and ifnotequal variants, and you can test the field.label against either a context variable, or a string.
You might be a lot happier creating a subclass of the form, excluding the offending field.
See http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#form-inheritance
class SmallerForm( MyForm ):
class Meta(MyForm.Meta):
exclude = [ title ]
{% for field in form %}
{% if field.name != 'field_name' %}
{{ field }}
{% endif %}
{% endfor %}

Categories