【问题标题】:How to call a non model field in django-tables2如何在 django-tables2 中调用非模型字段
【发布时间】:2015-11-03 03:11:46
【问题描述】:

我的应用 (app1) 中有几个模型。但是我想从在 app1 中创建的 djnago-tables2 中的另一个应用程序(app2)中创建的模型中调用一个字段。我怎么称呼它?我尝试了几种方法,但无法调用它。错误说Cannot resolve keyword u'xyz' into field.。请帮忙

【问题讨论】:

    标签: python html django django-models django-tables2


    【解决方案1】:

    如果您要在 Django-tables2 中使用多个模型,我建议您避免在表中定义模型,因此您的表可能是这样的:

    class NonModelTable(tables.Table):
        name = tables.columns.TemplateColumn(template_code=u"""{{ record.name }}""", orderable=True, verbose_name='Name')
        surname = tables.columns.TemplateColumn(template_code=u"""{{ record.surname }}""", orderable=True, verbose_name='Surname')
        address = tables.columns.TemplateColumn(template_code=u"""{{ record.address }}""", orderable=True, verbose_name='Address')
    
        class Meta:
            attrs = {'class': 'table table-condensed table-vertical-center', 'id': 'dashboard_table'}
            fields = ('name', 'surname', 'address')
            sequence = fields
            order_by = ('-name', )
    

    当你像这样定义表时,你可以传递一个字典列表来初始化表,但是这个字典需要有这 3 个字段(姓名、姓氏、地址),即使它们是空的。

    您没有提供有关您的确切数据结构的任何信息,所以我发明了这个只有 3 个字段的表,现在要使用不同的模型初始化这样的表,您应该生成一个 标准 列表像这样的字典:

    data = []
    object_1 = YourModel.objects.all()
    for object in object_1:
       data.append({'name': object.name, 'surname': object.type, 'address': ''})
    
    object_2 = Your2ndModel.objects.all()
    for object in object_2:
       data.append({'name': object.name, 'surname': object.status, 'address': object.warehouse})
    
    table = NonModelTable(data)
    
    return render(request, 'template.html', {... 'table':table,...})
    

    当然字段的数量是可定制的,你可以有你想要的名字的字段,但是当你初始化表时,字典列表中的字典必须遵循表结构,所有字典都必须包含表定义中出现的所有字段

    编辑:另一种选择

    如果您不想修改您的表格,您可以使用您传递给表格的数据生成一个字典列表,并在第一个模型结构之后附加来自其他模型的数据:

    1. 从您的 app1 中获取所有对象
    2. 生成包含表格所需字段的字典列表
    3. 从您的 app2 中获取所有对象
    4. 使用 app1 模型中的相同字典键附加来自 app2 的对象
    5. table = YourTable(data)初始化表

    【讨论】:

      猜你喜欢
      • 2013-05-14
      • 1970-01-01
      • 2013-01-24
      • 1970-01-01
      • 2021-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多