如果之前有人问过这个问题,我很抱歉,但是我找不到我的特定用例的答案。在
我有一个显示基本产品信息的表。产品的详细信息,如价格、销售额和卖家数量,都会定期地收集并存储在一个单独的数据库表中。现在,我想在前端的一个表中使用表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
...
现在如何使用这个返回的字典,并将其拆分为产品表中的列?除了我如何使用访问器之外,还有其他方法可以使用它吗?在
您可以使用
Accessor
来遍历dict,因此类似这样的方法应该有效:虽然这是有效的,排序也很好。为此,您的“currentState”方法有点碍事,您应该更改传递给表的QuerySet。此视图显示了该方法的工作原理:
^{pr2}$这将使用上面创建的注释简化表定义:
您可以找到完整的django项目at github
相关问题 更多 >
编程相关推荐