问题描述
我有两个数据模型,company
和contact_person
。它们以m2m变体形式链接:
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")
我想要的是每个名称都链接到它的联系方式,但是我正在解决访问器的内容错误,因此得到一个空表行。
我创建列表的方法是否错误[{"name": "Bart","id": 1},{"name": "Rita","id": 7},]
还是我只是在阅读文档方面有关于如何访问该列表的错误信息?
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)
解决方法
在寻求帮助后,结果证明我在使用LinkColumn
时走错了轨道。我使用TemplateColumn
解决了这个问题,我想分享我的方法-请随时发表评论或批评:
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")