【发布时间】:2020-07-22 08:49:11
【问题描述】:
我有一个零件清单(型号 1)和价格(型号 2)。我想将它们显示在 django-tables2 表中,以获取表中零件的历史价格:
models.py:
class Parts(models.Model):
name = models.CharField('Name', max_length=120, unique=True)
class Prices(models.Model):
price = models.DecimalField("Price", decimal_places=2, max_digits=8)
date = models.DateTimeField(default=timezone.now)
part = models.ForeignKey(Parts, on_delete=models.CASCADE)
tables.py:
class PriceHistoryTable(django_tables2.Table):
price = django_tables2.Column(accessor="prices_list", verbose_name="Price",)
date = django_tables2.Column(accessor="dates_list", verbose_name="Date",)
class Meta:
model = Parts
sequence = ("date", "price",)
我试图从两个列表中创建表格,因为我认为文档会建议 here (list of dicts) 在模型中使用这些方法:
def dates_list(self):
return [{"date": d.date} for d in Prices.objects.filter(part_id = self.id)]
def prices_list(self):
return [{"price": p.price} for p in Prices.objects.filter(part_id = self.id)]
但我最终在 django-tables2 中得到了一个表格,其中仅一行包含日期和价格的完整列表。
为价格创建查询集和为日期创建查询集的方法看起来如何,以便我可以将它用于 django-tables2?
编辑解决方案:
views.py
class PartTable(SingleTableView):
model = Parts
template_name = "gap/parts_detail.html"
table_class = PartPriceHistoryTable
queryset = Parts.objects.annotate(date=F("prices__date"),
price=F("prices__price")).order_by('price', 'date')
tables.py:
class PriceHistoryTable(django_tables2.Table):
price = django_tables2.Column(accessor="price", verbose_name="Price",)
date = django_tables2.Column(accessor="date", verbose_name="Date",)
class Meta:
model = Parts
sequence = ("date", "price",)
models.py 和上面一样
【问题讨论】:
标签: django django-models django-tables2