Accessing related models with django-tables2
Asked Answered
B

1

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.

Bernt answered 22/1, 2013 at 14:57 Comment(0)
D
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

Deckhand answered 22/1, 2013 at 16:42 Comment(4)
Thanks ustun! That's very helpful. foreigncolumn = tables.Column(accessor='foreignmodel.foreigncolumnname') in the table definition works a treat.Bernt
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.Deckhand
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_<column_name>(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).Ineffable
@TomaszGandor could you create a new Column with the accessor='id' and then call the related items in the render function?Parasang

© 2022 - 2024 — McMap. All rights reserved.