我想在 django-tables2 表上显示来自不同数据库表的数据。
我有几个应用程序,每个应用程序都有一些数据库表(每个表都在自己的文件中)。项目结构:
--project
-all
-overview
所有/模型/compound.py
class Compound (models.Model):
name = models.CharField(max_length = 100, unique = True, verbose_name="Probe")
dateAdded = models.DateField();
class Meta:
app_label = 'all'
所有/模型/probe.py
class Probe(Compound):
mechanismOfAction = models.CharField(max_length = 255, verbose_name="Mode of action")
def get_absolute_url(self):
return reverse('overview:probe_detail', args=[str(self.id)])
def __str__(self):
return f'{self.name}, {self.mechanismOfAction}'
class Meta:
app_label = 'all'
所有/模型/负控制.py
class NegativeControl(Compound):
probeId = models.ForeignKey(Probe, on_delete=models.CASCADE, related_name="controls", verbose_name="Control")
class Meta:
app_label = 'all'
概述/模型/usageData.py
class UsageData (models.Model):
cellularUsageConc = models.CharField (max_length = 50, null = True, verbose_name="Recommended concentration")
probeId = models.ForeignKey(Probe, on_delete=models.CASCADE, related_name="usageData")
def __str__(self):
return f'{self.cellularUsageConc}, {self.inVivoUsage}, {self.recommendation}'
class Meta:
app_label = 'overview'
所有/表.py
class AllProbesTable(tables.Table):
Probe = tables.Column(accessor="probe.name", linkify=True)
control = tables.Column(accessor="probe.controls")
mechanismOfAction = tables.Column()
cellularUsageConc = tables.Column(accessor="usageData.cellularUsageConc")
class Meta:
template_name = "django_tables2/bootstrap5-responsive.html"
全部/views.py
class AllProbesView(SingleTableView):
table_class = AllProbesTable
queryset = queryset = Probe.objects.all().prefetch_related('usageData', 'controls')
template_name = "all/probe_list.html"
所有/模板/所有/probe_list.html
{% load render_table from django_tables2 %}
{% render_table table %}
渲染的表格显示所有标题正确,并包含“探针”和“动作模式”的数据。对于“对照”,我得到“all.NegativeControl.None”,对于“推荐浓度”,我得到“-”。 为什么“推荐浓度”显示为“-”。
对于一个探头,可以有多个控件。我需要从所有控件名称(例如 control1、control2)创建一个字符串以将其显示在表中。我该怎么做?
这篇帖子很有帮助,但对我来说它不起作用。
我使用 Django 5.0.1 和 Python 3.12.1。
你们非常接近。在 Table 类中,您只需使用 related_name 进行访问,然后自定义渲染即可显示:
class AllProbesTable(tables.Table):
control = tables.Column(accessor="controls")
cellularUsageConc = tables.Column(accessor="usagedata")
# [...]
def render_control(self, record):
return [c.name for c in record.controls.all()]
def render_cellularUsageConc(self, record):
return [ud.cellularUsageConc for ud in record.usagedata.all()]