Django中通过子模型的子模型过滤Stock数据
通过ProductDepartment过滤Stock数据的优化方案
问题描述
我有三个Django模型:Stock、Product、ProductDepartment,需要通过ProductDepartment的id过滤Stock数据。目前用循环追加的方式处理,得到的列表难以按需求操作,希望得到优化方法。
模型代码
class Stock(models.Model): product = models.ForeignKey(Product, on_delete=models.DO_NOTHING) selling_price = models.DecimalField(max_digits=22, decimal_places=4, blank=True, null=True) # 其他字段... class Product(models.Model): bar_code = models.CharField(max_length=30, default='N/A', blank=True, null=True) title = models.CharField(max_length=30) product_code = models.CharField(max_length=50, default='N/A', blank=True, null=True) category = models.ForeignKey(DrugCategory, on_delete=models.DO_NOTHING, blank=True, null=True) department = models.ForeignKey(ProductDepartment, on_delete=models.DO_NOTHING) # 其他字段... class ProductDepartment(models.Model): title = models.CharField(max_length=30, blank=True, null=True) shortcut = models.CharField(max_length=30, blank=True, null=True) created_by = models.ForeignKey(User, on_delete=models.DO_NOTHING) created_at = models.DateTimeField(auto_now_add=True,blank=True, null=True) updated_at = models.DateTimeField(auto_now=True,blank=True, null=True) deleted = models.BooleanField(default=False)
解决方案
直接用Django的双下划线跨表查询,一次数据库查询就能得到符合要求的Stock QuerySet,后续可直接进行排序、分页、聚合等操作,完全替代循环追加的低效方式:
单个部门ID过滤
如果只需筛选某一个部门的Stock数据:
# 示例:过滤部门id为1的Stock target_department_id = 1 filtered_stocks = Stock.objects.filter(product__department__id=target_department_id)
多个部门ID过滤
如果需要同时筛选多个部门的Stock数据,使用__in:
# 示例:过滤部门id为1、3、5的Stock target_department_ids = [1, 3, 5] filtered_stocks = Stock.objects.filter(product__department__id__in=target_department_ids)
排除已删除部门的Stock
结合ProductDepartment的deleted字段,筛选未删除部门的Stock:
filtered_stocks = Stock.objects.filter( product__department__id=target_department_id, product__department__deleted=False )
得到的filtered_stocks是Django原生QuerySet对象,支持所有QuerySet操作,比如order_by('selling_price')排序、annotate做统计聚合、values提取指定字段等,比手动生成的普通列表灵活高效得多。
内容的提问来源于stack exchange,提问作者Tinashe Mphisa
相关产品推荐
相关产品推荐

