5

Can anyone provide a clear example of how to create a table object using django-tables2 that selects and presents data from multiple related models (ie a relational join)? The documentation implies this is possible, but does not say how.

In normal django the select_related() function works nicely, but I cannot work out how to implement this in django-tables2. I note there are other unanswered questions on similar topics.

Community
  • 1
  • 1
chill
  • 53
  • 1
  • 5

1 Answers1

5

First, select_related() is not required to access related data, it is there for performance reasons. For django-tables2, you need to define an accessor. An example is here: https://github.com/bradleyayers/django-tables2/issues/106

ustun
  • 6,941
  • 5
  • 44
  • 57
  • Thanks ustun! That's very helpful. `foreigncolumn = tables.Column(accessor='foreignmodel.foreigncolumnname')` in the table definition works a treat. – chill Jan 22 '13 at 21:50
  • Nice to hear that worked! A good tip is to search for keywords in the issues section of Githup repos, usually you will find solutions there in addition to SO. Could you mark the answer as accepted? Thanks. – ustun Jan 23 '13 at 08:31
  • 3
    What about going 1:N instead of N:1? For example - what if I want to concatenate all related models in the table cell? With the old `render_(self, record)` way this would be possible. I tried passing a `lambda record: ' '.join(...)` to `accessor=`, but it just gives me `None` (`--`). And I don't feel like adding such a method to the model, which I know that it works. I just don't think it belongs to the "Model Layer", but to the "Table Layer" (`tables.py`). – Tomasz Gandor Apr 22 '14 at 23:26
  • @TomaszGandor could you create a new Column with the `accessor='id'` and then call the related items in the render function? – DanH May 15 '15 at 13:13