通过Django中的另一个模型查询模型

时间:2021-03-15 09:30:52

标签: django

我的应用中有一个名为 Demand 的模型

class DemandFlows(models.Model):
 
    kit = models.ForeignKey(Kit, on_delete=models.CASCADE)
    
class Demand(models.Model):

    demand_flows = models.ManyToManyField(DemandFlows)
    delivery_month = models.DateTimeField(blank=True, null=True)

从这个模型中,我得到了 monthyear 以及当月使用的工具包,如下所示:

    d_o = Demand.objects.all()
    for i in d_o:
        print("month", i.delivery_month)
        m = i.delivery_month
        print("m", m.month)
        print("y", m.year)
        for k in i.demand_flows.all():
            print("k", k.kit.pk)

现在我有另一个模型 Allotment,我如何查询这个模型,以便获得 kit 和我在 {{1} 之前获得的特定月份的 alloted_quantity 的总和} 模型?

分配:

Demand

例如

我从 class AllotmentFlow(models.Model): kit = models.ForeignKey(Kit, on_delete=models.CASCADE) alloted_quantity = models.IntegerField(default=0) class Allotment(models.Model): transaction_no = models.IntegerField(default=0) dispatch_date = models.DateTimeField(default=datetime.now) flows = models.ManyToManyField(AllotmentFlow) 得到以下信息:

demand

那么我如何知道 2020 年 12 月的 m 12 y 2020 k 3 k 4 k 5 k 7 k 8 k 9 k 10 3,4,5,7,8,9,10 的 alloted_quantity

套件型号:

kit

3 个答案:

答案 0 :(得分:1)

我认为您可以在这里使用 GroupBy 功能:

from django.db.models import Sum

Demand.objects.values('delivery_month__year', 'delivery_month__month').annotate(allotment_qty=Sum('demand_flows__kit__allotmentflow__ alloted_quantity')).values('delivery_month__year', 'delivery_month__month', 'allotment_qty')

可以在values() documentation中找到更多信息。

答案 1 :(得分:0)

试试这个,这将为您提供 alloted_quantity 给定日期的套件。

for k in i.demand_flows.all():
    allotment_flow = AllotmentFlow.objects.filter(
        kit=k.id,
        allotment__dispatch_date__month=m.month,
        allotment__dispatch_date__year=m.year,
    )
    print('qty',allotment_flow[0].alloted_quantity)

答案 2 :(得分:0)

for demand in Demand.objects.all(): # We cycle through demands

    # We print the relevant info
    print(f"Month : {demand.delivery_month}")
    print(f"M : {demand.delivery_month.month}")
    print(f"Y : {demand.delivery_month.year}")


    total_allotted_quantity = 0  # We initialize the variable that we'll use to sum the month's allotted quantities

    for demand_flow in demand.demand_flow.all():  # We cycle through the kit ids of the selected month
        partial_allotted_quantity = 0
        for allotment_flow in  AllotmentFlow.objects.filter(kit=Kit.objects.get(id=demand_flow.kit.id)): # Returns a list of AllotmentFlow elements that are associated with that specific Kit
            partial_allotted_quantity += allotment_flow.alloted_quantity
        total_allotted_quantity += partial_allotted_quantity
    print(total_allotted_quantity)