单个 table 的两个模型的查询集

Queryset from two models for a single table

我有一份零件清单(模型 1)和价格(模型 2)。我想在 django-tables2 table 中显示它们以获取 table:

中零件的历史价格

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",)

我尝试从两个列表创建 tables,因为我认为文档会建议 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 中得到了一个 table,它仅在一行中包含完整的日期和价格列表。

为价格创建查询集和为日期创建查询集的方法看起来如何,以便我可以将其用于 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 和上面一样

你可以尝试使用F() expression用queryset注解date和price的值,在table中通过accessor访问(也可以不访问,定义与注解变量相同的字段名即可) ].例如:

# table class
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",)

# example implementation
from django.db.models import F

queryset = Parts.objects.annotate(date=F('prices__date'), price=F('price__price')).order_by('parts', 'date')
table = PriceHistoryTable(queryset)

for item in table.as_values():
    print(item)

# view

class PartTable(SingleTableView):
    template_name = "gap/parts_detail.html"
    table_class = PartPriceHistoryTable
    table_pagination = {"per_page": 10}    
    queryset = Parts.objects.annotate(date=F("prices__date"), price=F("prices__price")).order_by('price', 'date')