Suppose i have this model
class Model():
var1 = models.TextField()
var2 = models.FloatField()
var3 = models.FloatField()
var4 = models.FloatField()
Now I want to have one template which i can use for all models. My requirement is
- I want to display var1 , var2 , var 4 in view not var 3
- In the template , i don't want to hard code field names like var1 , var2, var3 which i will make the heading of table , so i would like like to get that from array
- I want all the data corresponding to those vars
Basically i want something like
Object_List
which contains the field names
and field values
both for all rows
in DB table
Object_List
-- I will grab form SELECT var1, var2, var4 from table
so that in template i can use
{% for field in Object_List.fields %}
<th>{{ field }}</th>
{% endfor %}
Then for data i can use
{% for object in Object_List.objects %}
<tr>
{% for field in object %}
<td>{{ value }}</td>
{% endfor %}
</tr>
{% endfor %}
I am not sure if i explained it clearly . is it possible to achieve something like that. The main requirement is that i want only selected fields to display in template not all fields mentioned in Model
The simplest way you can get the list of objects of an attribute is to first get a query-set of that attribute alone using values_list then converting the django query-set to a python set using set() and finally to a list using list() .
Django values_list() is an optimization to grab specific data from the database instead of building and loading the entire model instance.
try the following code : def read_data(db_name,tbl_name): details = sfconfig_1. dbdetails connect_string = 'DRIVER=ODBC Driver 17 for SQL Server;SERVER={server}; DATABASE={database};UID={username}\ ;PWD={password};Encrypt=YES;TrustServerCertificate=YES'.
Seems like the obvious way to do this is to use a values
query:
objects = Model.objects.values('var1', 'var2', 'var4')
This gives you a list of dictionaries, each one mapping field name to field value. So you can get your header row from the first of these:
{% for object in objects %}
{% if forloop.first %}
<th>
{% for fieldname in object.keys %}<td>{{ fieldname }}</td>{% endfor %}
</th>
{% endif %}
<tr>
{% for value in object.values %}<td>{{ value }}</td>{% endfor %}
</tr>
{% endfor %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With