blackwindow
blackwindow

Reputation: 437

How to call a non model field in django-tables2

I have several models in my app(app1). But I want to call one field from a model created in my another app(app2) in my djnago-tables2 created in app1. How can I call it? I tried several ways but couldn't able to call it. error says Cannot resolve keyword u'xyz' into field.. Please help

Upvotes: 2

Views: 1912

Answers (1)

AlvaroAV
AlvaroAV

Reputation: 10563

If you are going to use multiple models in a Django-tables2 I recommend you to avoid defining a model in your table, so your table could be like:

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', )

When you define the table like this you can pass a list of dictionaries to initialize the table, but this dictionaries need to have this 3 fields (name, surname, address) even they are empty.

You didn't provide any info about your exact data structure so I invented this table with only 3 fields, to initialize now a table like that using different models, you should generate a standard list of dicts like:

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,...})

Of course the number of fields are customizable, you can have as many fields as you want with the names you wish BUT when you initialize de table, the dicts within the list of dicts has to follow the table structure, all the dicts must have all the fields that appears in the table definition

EDIT: Another option

If you don't want to modify your table, you could generate a list of dicts with the data you're passing to the table, and append the data from other models following the first model structure:

  1. Get all the objects from your app1
  2. Generate a list of dicts with the required fields for the table
  3. Get all the objects from your app2
  4. Append the objects from your app2 with the same dict keys from your app1 model
  5. Initialize the table with table = YourTable(data)

Upvotes: 4

Related Questions