gpt4 book ai didi

python - 显示对象表 django

转载 作者:太空狗 更新时间:2023-10-29 21:26:58 26 4
gpt4 key购买 nike

我需要使用 Django 从我的数据库中显示一个表。显而易见的方法是手动键入表标题并循环遍历 model.objects.all() 的查询结果。但是,由于很懒,我想自动执行此操作,即通过内省(introspection)从模型加载所有字段以显示为列标题,并加载所有字段值以显示为行。这种方法还可以在以后为我节省一些时间,因为我不必在模型更改时更新模板代码。我让它工作,但有两个问题:

  1. 我找不到加载 AutoField 字段 (id) 值的方法,所以我必须切掉 ID 列。
  2. 代码看起来很乱,尤其是使用了随机模板标签。

这是我的代码。请注意,代码工作正常,所以我将跳过所有导入,因为它们是正确的:

views.py I use serializers to serialize the data, a trick I read somewhere on stackoverflow

def index(request):
fields = MyModel._meta.fields
data = serializers.serialize("python", MyModel.objects.all())
context_instance = RequestContext(request, {
'data' : data,
'fields' : fields,
})
return TemplateResponse(request, 'index.html', context_instance)

template/index.html: note that I have to slice off the ID column by slicing off the first element of the fields list

{% with fields|slice:"1:" as cached_fields %}
<table>
<thead>
<tr>
{% for field in cached_fields %}
<th>{% get_verbose_name field %}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for instance in data %}
<tr>
{% for field in cached_fields %}
<td>{% get_value_from_key instance.fields field %}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
{% endwith %}

templatetags/extra_tags.py

# tag to get field's verbose name in template 
@register.simple_tag
def get_verbose_name(object):
return object.verbose_name

# tag to get the value of a field by name in template
@register.simple_tag
def get_value_from_key(object, key):
# is it necessary to check isinstance(object, dict) here?
return object[key.name]

最佳答案

serializers.serialize("json or xml", Model.objects.all()) 格式返回id字段;可能不是您要找的东西,但一些 jQuery 网格插件可以进一步自动化该任务。

关于python - 显示对象表 django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14615847/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com