Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i extract the fieldnames and values from Django query

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

  1. I want to display var1 , var2 , var 4 in view not var 3
  2. 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
  3. 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

like image 534
user1 Avatar asked Jul 07 '11 09:07

user1


People also ask

How do you get or view all the items in a model in Django?

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() .

What is values and values_list in Django?

Django values_list() is an optimization to grab specific data from the database instead of building and loading the entire model instance.

How do you get field names when running plain query in Django?

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'.


1 Answers

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 %}
like image 198
Daniel Roseman Avatar answered Nov 14 '22 23:11

Daniel Roseman