3

Can anyone provide a clear example of how to show a table using django-tables2 that selects and presents data from two(or more) related models?

I've found lots of posts about that, most of them quite old, and none really a working example.

These are my models:

class Person(models.Model):
    name = models.CharField(verbose_name="Name",max_length=50)
    fname = models.CharField(verbose_name="F.Name",max_length=50)

class Speech(models.Model):
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    said = models.CharField(verbose_name="Said",max_length=50)

I simply want to show a table with columns "Name, F.Name, Said". Which is the best way? And with multiple tables?

Thanks in advance.

Max Iskram
  • 147
  • 10

1 Answers1

8

Well, nobody answered my question. After digging and trying I found a way to show fields from related models in one table. The thing is the table definition into tables.py should be like this:

class SpeechTable(tables.Table):
    name = tables.Column(accessor='person.name')
    fname = tables.Column(accessor='person.fname')
    said = tables.Column()
    class Meta:        
        attrs = {"class": "paleblue"}

Not sure if this is the best way, but it is simple and works fine.

Max Iskram
  • 147
  • 10