【发布时间】:2018-10-01 08:03:44
【问题描述】:
假设我的项目中有一个Product 模型:
class Product(models.Model):
price = models.IntegerField()
并且我想要一些统计数据(假设我想要跟踪价格随时间的变化):
class ProductStatistics(models.Model):
created = models.DateTimeField(auto_add_now=True)
statistics_value = models.IntegerField()
product = models.ForeignKey(Product)
@classmethod
def create_for_product(cls, product_ids):
statistics = []
products = Product.objects.filter(id__in=products_ids)
for product in products:
statistics.append(
product=product
statistics_value=product.price
)
cls.objects.bulk_create(statistics)
@classmethod
def get_latest_by_products_ids(cls, product_ids):
return None
我在实现get_latest_by_products_ids 方法时遇到问题。我只想要最新的统计数据,所以我不能这样做:
@classmethod
def get_latest_by_products_ids(cls, product_ids):
return cls.objects.filter(product__id__in=product_ids)
因为这会返回我收集到的所有统计数据。如何将查询限制为每个产品的最新查询?
编辑 我正在使用 PostgreSQL 数据库。
【问题讨论】:
标签: django postgresql django-orm