[Django]-Django-tables2: How to use accessor to bring in foreign columns?

20👍

The model name in the accessor parameter of the column should be lowercase.

Use accessor='student.netID' instead of accessor='Student.netID'.

👤Noah

3👍

When using the accessor parameter, you have to use the field name stated in the Model that has the foreign key, and then select which field from that table you want to use.

So, for these models:

#models.py
class Description_M(models.Model):
   id_hash = models.CharField(db_column='Id_hash', primary_key=True, max_length=22)
   description = models.CharField(db_column='Description', max_length=255, blank=True, null=True)

class GeoCodes(models.Model):
    geo = models.CharField(db_column='Geo', primary_key=True, max_length=5)
    city_name = models.CharField(db_column='City', max_length=150, blank=True, null=True)

class RefSources(models.Model):
    id_source   = models.IntegerField(db_column='Id_source', primary_key=True,)  
    source_name   = models.CharField(db_column='Source', max_length=150, blank=True, null=True)  

class Price(models.Model):
    id_hash = models.ForeignKey(Description_M, models.DO_NOTHING, db_column='Id_hash')
    date= models.ForeignKey(DateTime, models.DO_NOTHING, db_column='Date')
    geo = models.ForeignKey(GeoCodes, models.DO_NOTHING, db_column='Geo')
    id_source = models.ForeignKey(RefSources, models.DO_NOTHING, db_column='Id_source')  # Field name made lowercase.
    price = models.FloatField(db_column='Price',primary_key=True, unique=False,default=None)

When using the foreign key to pull fields from that table, you have to:

class price_table(tables.Table):
    description = tables.Column(accessor = 'id_hash.description')
    city = tables.Column(accessor = 'geo.city_name')
    source = tables.Column(accessor = 'id_source.source_name')
    class Meta:
        model = Price
        fields = ['date','price']
        sequence = ['description ','date','city ','source','price']
        template_name = 'django_tables2/bootstrap.html'

Leave a comment