I have two data models, company
and contact_person
. They are linked in a m2m variant:
models.py:
class ContactPerson(models.Model):
name = models.CharField('first name', max_length=120)
@property
def contact_name(self):
return [self.name, self.id]
class Customer(models.Model):
name = models.CharField('company name', max_length=120)
contact_persons = models.ManyToManyField(ContactPerson, blank=True, null=True)
@property
def contacts(self):
persons = []
for c in self.contact_persons.all():
persons.append({"name": c.contact_name[0], "id": c.contact_name[1]})
return persons
tables.py:
class CustomerTable(django_tables2.Table):
name = django_tables2.LinkColumn("customer-detail",
args=[django_tables2.A("pk")])
contacts = django_tables2.LinkColumn("contact-detail",
args="contacts__id",
accessor="contacts__name",
verbose_name="contacts")
class Meta:
model = Customer
sequence = ("name", "contacts")
What I want is that every name is linked to it's contact detail, but I am addressing the content of the accessor wrong, therefore get an empty table row.
Is my method with creating a list wrong [{"name": "Bart", "id": 1}, {"name": "Rita", "id": 7},]
or did I just read the docs wrong on how to access that list?
views.py:
class CustomerListView(SingleTableView):
model = Customer
context_object_name = 'customer'
table_class = CustomerTable
template_name = "customerlist.html"
def get_queryset(self):
qs = super(CustomerListView, self).get_queryset()
return list(qs)
Turned out after some help I was on the wrong track with using LinkColumn
. I solved it with using a TemplateColumn
and I wanted to share my approach - please feel free to comment or criticize:
models.py:
class ContactPerson(models.Model):
name = models.CharField('name', max_length=120)
@property
def name(self):
return self.name
class Customer(models.Model):
name = models.CharField('company name', max_length=120)
contact_persons = models.ManyToManyField(ContactPerson, blank=True)
tables.py:
class CustomerTable(django_tables2.Table):
TEMPLATE = '''
{% for contact in record.contact_persons.all %}
<a href="{% url "contact-detail" contact.pk %}">{{ contact.name }}</a><br/ >
{% endfor %}
'''
contacts = django_tables2.TemplateColumn(empty_values=(),
orderable=False,
template_code=TEMPLATE)
name = django_tables2.LinkColumn("customer-detail",
args=[django_tables2.A("pk")])
class Meta:
model = Customer
sequence = ("name", "contacts")