from django_tables2.utils import Accessor class Person: def __init__(self, name, age): self.name = name self.age = age people = [Person("Alice", 25), Person("Bob", 30)] table_data = [ {"name_age": Accessor("name_age")}, ] for person in people: row = {cell_name: getattr(person, cell_name) for cell_name in table_data[0].keys()} print(row)
from django_tables2.utils import Accessor class Person: def __init__(self, name, age, address=None): self.name = name self.age = age self.address = address people = [Person("Alice", 25), Person("Bob", 30, "123 Main St")] table_data = [ {"name": Accessor("name")}, {"age": Accessor("age")}, {"address": Accessor("address.street")}, ] for person in people: row = {cell_name: Accessor(cell_name).resolve(person) for cell_name in table_data[0].keys()} print(row)In this example, we again create a `Person` class with `name`, `age`, and optional `address` properties. We define a `table_data` list with three cells, one for each property. We use the `Accessor` class to access the `street` property of the `address` object for the last cell. Finally, we again iterate over the `people` list, creating a dictionary for each `Person` object with the keys in `table_data`, but this time we use `Accessor.resolve()` to get the value for each cell. Package library: `django-tables2`.