我使用的是django v1.10.2
我正在尝试创建动态报表,以便将字段和条件以及主要的ORM模型信息存储到数据库中。在
我生成动态报表的代码是
class_object = class_for_name("app.models", main_model_name)
results = (class_object.objects.filter(**conditions_dict)
.values(*display_columns)
.order_by(*sort_columns)
[:50])
所以main_model_name
可以是任何东西。
这非常有用,只是有时main_model
的关联模型有choicefield
。在
所以其中一个报告main_model
是Pallet
。Pallet
有很多PalletMovement
。
我的显示列是:serial_number
,created_at
,pallet_movement__location
前两列是属于Pallet
模型的字段。
最后一个来自PalletMovement
结果是PalletMovement
模型如下所示:
既然查询集将返回原始值,那么我如何利用PalletMovement
模型中的choicefield
来确保pallet_movement__location
给出AB-Delaware
或{
请记住,main_model
可以是任何内容,这取决于我在数据库中存储的内容。在
大概,我可以在数据库中存储更多的信息,以帮助我更好地过滤和显示数据。在
创建templatetag的另一种方法是:
这将显示外键字段的初始数据值,而不是id
values()
方法返回表示字段名和相应值的键值对字典。在例如:
型号:
查询:
^{pr2}$结果:
现在,您可以像处理普通字典一样操作此结果:
您甚至可以将其转换为一个函数,以获得更好的可重用性:
我建议使用
update()
和get()
方法,因为它们可以避免潜在的错误,例如:search_key
不存在于choice_dict
中,则get()
将返回{update()
将尝试更新给定的键值对(如果存在),否则将把它添加到字典中。在如果以上内容将在数据的模板表示中使用,则可以创建一个custom template filter:
在这里多看一眼:Django: How to access the display value of a ChoiceField in template given the actual value and the choices?
您可以使用
get_foo_display
在模板中:
或者
^{pr2}$[编辑:]正如评论中指出的,在调用
values()
时,这将不起作用相关问题 更多 >
编程相关推荐