【发布时间】:2022-01-13 15:01:44
【问题描述】:
我有两个问题。其中一个有产品id和销售金额,另一个有产品id和产品价格。
query_product = Model1.objects.filter(...).values_list('ProductID', 'ProductPrice')
query_sale = Model2.objects.filter(...).values_list('SaleProductID', 'ProductAmount')
我想计算 IF SaleProductID = ProductID, Sum(F('ProductPrice')*F('ProductAmount')。但是,我找不到如何通过查询来执行此操作。注意:Model2 具有 Model1 的外键。
你有什么建议吗?谢谢!
编辑:我想在 PBGelenSiparis 类的管理站点上显示总金额。这是翻译后的完整模型;
class PBUrun(models.Model):
PBUrunNu = models.IntegerField(verbose_name='Product Code')
PBUrunName = models.CharField(verbose_name='Product Name', max_length=200)
PBUrunPrice = models.DecimalField(verbose_name='Product Price', max_digits=10, decimal_places=2)
class PBGelenSiparis(models.Model):
pburun = models.ForeignKey(PBUrun, verbose_name='Choose Product', on_delete=models.CASCADE )
PBGelSipNu = models.AutoField(verbose_name='Order Number', primary_key = True)
def GelenSiparisTutari(self):
find_ordered_products = PBGelenSiparisUrun.objects.filter(pbgelensiparis_id = self.PBGelSipNu)\
.values('pburun_id')
order_product_price = PBUrun.objects.filter(PBUrunNu__in = siparis_urunlerini_bul).values_list('PBUrunNu','PBUrunFiyat')
order_product_amount = PBGelenSiparisUrun.objects.filter(pbgelensiparis_id = self.PBGelSipABNu).values_list('pburun_id','PBGelSipUrunAdet')
class PBGelenSiparisUrun(models.Model):
pburun = models.ForeignKey(PBUrun, verbose_name='Choose Product', on_delete=models.CASCADE )
pbgelensiparis = models.ForeignKey(PBGelenSiparis, verbose_name='Order', on_delete=models.CASCADE)
PBGelSipUrunAdet = models.IntegerField(verbose_name='Order Quantity')
【问题讨论】:
-
这两个模型是否通过外键关联?你能分享两个模型吗
-
感谢您的回答。 Model2 对 Model1 有 fk。我已经添加了完整的模型。
-
Model2 == PBGelenSiparisUrun 和 Model1 == PBUrun,对吧?
-
其实就是Model1 == PBUrun, Model2 = PBGelenSiparisUrun and Model3 == 'a model with order amount'。但是,您的子查询建议可能会有所帮助。我会尝试发布结果。
标签: mysql django django-queryset django-orm