I am trying to use django-tables to create a sortable table out of some Models.
http://elsdoerfer.name/docs/django-tables/types/models.html#spanning-relationships says that I can span through relationships, but I have difficulty doing it “backwards”.
Here are my models and the table:
class Book(Model):
isbn = ISBNField("ISBN", primary_key=True, editable=True, blank=True, null=False)
class SomeInfo(Model):
book = OneToOneField(Book, primary_key=True, editable=False, blank=False, null=False, verbose_name = _('ISBN'), related_name='someinfo')
title = CharField(_("Title"), editable=False, blank=False, null=True, max_length=250)
class MyInfo(Model):
book = OneToOneField(Book, primary_key=True, editable=False, blank=False, null=False, verbose_name = _('ISBN'), related_name='myinfo')
average_price = DecimalField(_("Average price"), editable=False, null=True, max_digits=6, decimal_places=2)
class Query(Model):
book = ForeignKey(Book, editable=True, blank=True, null=True, verbose_name = _('ISBN'))
max_price = DecimalField(_('Maximum price'), null=True, max_digits=6, decimal_places=2)
class MyTable(ModelTable):
my_average_price = tables.Column(data="book__myinfo__average_price")
my_title = tables.Column(data="book__someinfo__title")
class Meta:
model = Query
When trying to use for example my_average_price in a template, I get this error:
TemplateSyntaxError at /list/
Caught ValueError while rendering: Could not resolve myinfo from book__myinfo__average_price
Any ideas how to make it work?
All columns, also the ones from the related relationships, need to be sortable.
This works for me, provided that a related SomeInfo or MyInfo instance exists. The error should only be raised if that is not the case. I.e., each book in the table would need to have SomeInfo and MyInfo attached.
This is because the code in
django_tables/models.py:BoundModelRow._default_renderwill raise this error if one of the attributes in the chain does not exist, which is the case here if a related instance is missing: Book.myinfo does not exist as an attribute if no MyInfo exists for the Book instance.This would probably need to be considered a bug in django-tables. Rather than just reversing through the object attributes, it should look at instance._meta at which database fields have actually been defined. If it determines that a reverse OneToOne accessor exists, but no corresponding attribute does, it would then just assume a null value rather than raising an exception.
I’ve reported this as a bug here: https://github.com/miracle2k/django-tables/issues/issue/11 However, I’m not sure when I’ll get to work on it. Patches are certainly welcome.