Django ORM,如何使用values()并仍然使用choicefield?

2024-09-30 14:30:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的是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_modelPallet
Pallet有很多PalletMovement
我的显示列是:serial_numbercreated_atpallet_movement__location

前两列是属于Pallet模型的字段。 最后一个来自PalletMovement

结果是PalletMovement模型如下所示:

^{pr2}$

既然查询集将返回原始值,那么我如何利用PalletMovement模型中的choicefield来确保pallet_movement__location给出AB-Delaware或{}的显示?在

请记住,main_model可以是任何内容,这取决于我在数据库中存储的内容。在

大概,我可以在数据库中存储更多的信息,以帮助我更好地过滤和显示数据。在


Tags: columnsname模型信息数据库modelobject报表
3条回答

创建templatetag的另一种方法是:

{{form.choicefield.1}}

这将显示外键字段的初始数据值,而不是id

values()方法返回表示字段名和相应值的键值对字典。在

例如:

型号:

class MyModel(models.Model):
    name = models.CharField()
    surname = models.CharField()
    age = models.IntegerField()
    ...

查询:

^{pr2}$

结果:

< Queryset [{'name': 'moutafis', 'surname': 'john'}] >

现在,您可以像处理普通字典一样操作此结果:

if main_model_name is 'PalletMovement':
    # Make life easier
    choices = dict(PalletMovement.WAREHOUSE_CHOICES)

    for item in result:
        item.update({ 
            pallet_movement__location: verbal_choice.get(
                pallet_movement__location, pallet_movement__location)
        })

您甚至可以将其转换为一个函数,以获得更好的可重用性:

def verbalize_choices(choices_dict, queryset, search_key):
    result = queryset        

    for item in result:
        item.update({ search_key: choices_dict.get(search_key, search_key) })

    return result

verbal_result = verbalize_choices(
                    dict(PalletMovement.WAREHOUSE_CHOICES),
                    result,
                    'pallet_movement__location'
                )

我建议使用update()get()方法,因为它们可以避免潜在的错误,例如:

  • search_key不存在于choice_dict中,则get()将返回{}的值
  • update()将尝试更新给定的键值对(如果存在),否则将把它添加到字典中。在

如果以上内容将在数据的模板表示中使用,则可以创建一个custom template filter

@register.filter(name='verbalize_choice')
def choice_to_verbal(choice):
    return dict(PalletMovement.WAREHOUSE_CHOICES)[choice]

在这里多看一眼:Django: How to access the display value of a ChoiceField in template given the actual value and the choices?

您可以使用get_foo_display

在模板中:

{{ obj.get_location_display }}

或者

^{pr2}$

[编辑:]正如评论中指出的,在调用values()时,这将不起作用

相关问题 更多 >