【问题标题】:Is there a way i can join two tables and get the sum of duplicated field in Django有没有办法我可以加入两个表并获得 Django 中重复字段的总和
【发布时间】:2021-04-11 09:19:11
【问题描述】:

我有一个模型 WarehouseTrade Account 和 WarehouseStorage Account 它看起来像这样:-------

class WarehouseStorageAccount(models.Model):
    warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, null=True)
    item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True)
    grade = models.CharField(max_length=5, choices=ITEM_GRADE_CHOICES)
    bags = models.IntegerField(default=0)
    gross_weight = models.DecimalField(max_digits=20, decimal_places=3, default=0)
    net_weight = models.DecimalField(max_digits=20, decimal_places=3, default=0)
    updated = models.DateTimeField(auto_now=True)

class WarehouseTradeAccount(models.Model):
    warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, null=True)
    item = models.ForeignKey(Item, on_delete=models.CASCADE)
    grade = models.CharField(max_length=5, choices=ITEM_GRADE_CHOICES)
    bags = models.IntegerField(default=0)
    gross_weight = models.DecimalField(max_digits=20, decimal_places=3, default=0)
    net_weight = models.DecimalField(max_digits=20, decimal_places=3, default=0)
    updated = models.DateTimeField(auto_now=True)

我正在尝试获取两个帐户中的所有数据,但如果两者之间存在重复,则应将其汇总。 我已经能够使用以下代码通过 SQL 实现这一点:

SELECT 
    data.warehouse_id AS Warehouse, 
    data.item_id  AS Item,
    data.grade  AS Grade,
    SUM((data.net_weight)) AS Net_WEIGHT,
    SUM((data.gross_weight)) AS Gross_WEIGHT,
    SUM((data.bags)) AS Bags 
FROM 
    (SELECT warehouse_id, item_id, net_weight, grade, gross_weight, bags FROM public.inventory_warehousestorageaccount
    UNION ALL
    SELECT warehouse_id, item_id, net_weight, grade, gross_weight, bags
   FROM public.inventory_warehousetradeaccount
    ) data
    
GROUP BY data.warehouse_id, data.item_id, data.grade

我尝试使用 union 来连接两个表,然后得到聚合结果,但我一直收到错误

wt = WarehouseTradeAccount.objects.all()
ws = WarehouseStorageAccount.objects.all()
w=wt.union(ws)
w.aggreate(new_net_weight=Sum('net_weight')

如何在 Django 中复制它?

【问题讨论】:

    标签: django django-models django-orm


    【解决方案1】:

    其实我没明白你的意思

    如果两者之间有重复,应该总结一下

    要删除重复项吗?

    attributes = ('warehouse','item','grade'....)
    result = []
    
    wt = WarehouseTradeAccount.objects.all()
    ws = WarehouseStorageAccount.objects.all()
    
    for wtobj, wsobj in zip(wt,ws):
        for attribute in attributes:
            if getattr(wtobj, attribute) != getattr(wsobj, attribute):
                result.append(wtobj, wsobj)
                break
        else:
            result.append(wtobj)       
    

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多