Django-Tables2添加额外列从词典中

2024-04-29 02:36:38 发布

您现在位置:Python中文网/ 问答频道 /正文

如果之前有人问过这个问题,我很抱歉,但是我找不到我的特定用例的答案。在

我有一个显示基本产品信息的表。产品的详细信息,如价格、销售额和卖家数量,都会定期地收集并存储在一个单独的数据库表中。现在,我想在前端的一个表中使用表2显示基本的产品信息和刮取的详细信息。为此,我在我的产品模型中编写了一个函数来获取最新的详细信息并将它们作为字典返回,这样我就可以使用单个访问器调用了。在

# models.py

class Product(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)

    name = models.CharField(max_length=256)
    brand = models.ForeignKey(Brand)
    category = models.CharField(max_length=128, choices=CATEGORY_CHOICES)

    def __unicode__(self):
        return self.name

    def currentState(self):
        currentDetailState = ProductDetailsState.objects.filter(
            product=self
        ).latest('created_at')

        # return current details as a dictionary
        return {
            price: currentDetailState.price,
            num_sellers: currentDetailState.num_sellers,
            num_sales: currentDetailState.num_sales
        }


class ProductDetailsState(models.Model):
    product = models.ForeignKey(Product)
    created_at = models.DateTimeField(auto_now_add=True)

    price = models.DecimalField(max_digits=6, decimal_places=2, null=True)

    num_sellers = models.IntegerField(null=True)
    num_sales = models.IntegerField(null=True)

    def __unicode__(self):
        return self.created_at



# tables.py

class ProductTable(tables.Table):
    productBrand = tables.Column(
        accessor=Accessor('brand.name'),
        verbose_name='Brand'
    )
    currentRank = tables.Column(
        accessor=Accessor('currentRank')
    )

    class Meta:
        model = Product
        ...

现在如何使用这个返回的字典,并将其拆分为产品表中的列?除了我如何使用访问器之外,还有其他方法可以使用它吗?在


Tags: nameselftruetablesreturn产品models详细信息
1条回答
网友
1楼 · 发布于 2024-04-29 02:36:38

您可以使用Accessor来遍历dict,因此类似这样的方法应该有效:

class ProductTable(tables.Table):
    # brand is the name of the model field, if you use that as the column name, 
    # and you have the __unicode__ you have now, the __unicode__ will get called, 
    # so you can get away with jus this:
    brand = tables.Column(verbose_name='Brand')
    currentRank = tables.Column()

    # ordering on the value of a dict key is not possible, so better to disable it.
    price = tables.Column(accessor=tables.A('currentState.price'), orderable=False)
    num_sellers = tables.Column(accessor=tables.A('currentState.num_sellers'), orderable=False)
    num_sales = tables.Column(accessor=tables.A('currentState.num_sales'), orderable=False)

    class Meta:
        model = Product

虽然这是有效的,排序也很好。为此,您的“currentState”方法有点碍事,您应该更改传递给表的QuerySet。此视图显示了该方法的工作原理:

^{pr2}$

这将使用上面创建的注释简化表定义:

class ProductTable(tables.Table):
    brand = tables.Column(verbose_name='Brand')
    currentRank = tables.Column()

    price = tables.Column()
    num_sellers = tables.Column()
    num_sales = tables.Column()

    class Meta:
        model = Product

您可以找到完整的django项目at github

相关问题 更多 >