gpt4 book ai didi

Django - 获取每个关系中的最新对象

转载 作者:行者123 更新时间:2023-11-29 14:30:28 25 4
gpt4 key购买 nike

假设我的项目中有一个 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 数据库。

最佳答案

Querysets already have a last() method (还有一个 first() 方法 FWIW)。唯一的问题是你想将什么定义为“最后”,因为这取决于查询集的顺序......但是假设你想要最后一个创建日期(created 字段),你也可以 use the lastest() method :

@classmethod
def get_latest_by_products_ids(cls, product_ids):
found = []
for pid in products_ids:
found.append(cls.objects.filter(product_id=pid).latest("created"))
return found

作为旁注:Django's coding style is to use the Manager (and eventually the Queryset) for operations working on the whole table ,所以你应该创建一个自定义管理器,而不是在你的模型上创建类方法:

class productStatisticManager(models.Manager):

def create_for_products(self, product_ids):
statistics = []
products = Product.objects.filter(id__in=products_ids)
for product in products:
statistics.append(
product=product
statistics_value=product.price
)
self.bulk_create(statistics)

def get_latest_by_products_ids(cls, product_ids):
found = []
for pid in products_ids:
last = self.objects.filter(product_id=pid).latest("created")
found.append(last)
return found

class ProductStatistics(models.Model):
created = models.DateTimeField(auto_add_now=True)
statistics_value = models.IntegerField()
product = models.ForeignKey(Product)

objects = ProductStatisticManager()

关于Django - 获取每个关系中的最新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52586866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com