开发者

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 wo开发者_JS百科uld 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


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 %}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜