在多个字段上的Django Rest连接模型

问题描述 投票:0回答:1

我有以下两种型号。

这些模型按月存储每个项目的预算销售数据和实际销售数据。

# To test join on multiple keys

class ActualSales(models.Model):
    time_id = models.CharField(max_length=8)
    project = models.CharField(max_length=100)
    actual_sales = models.DecimalField(max_digits=20, decimal_places=3)
    adjustment = models.DecimalField(max_digits=20, decimal_places=3)


class BudgetSales(models.Model):
    time_id = models.CharField(max_length=8)
    project = models.CharField(max_length=100)
    budget_sales = models.DecimalField(max_digits=20, decimal_places=3)

数据将看起来像这样。

Model A

| time_id |  project  | sales | adjustment |
+---------+-----------+-------+------------+
| 2019JAN | Project A |  1000 |         10 |
| 2019JAN | Project B |  2500 |          5 |
| 2019FEB | Project A |  1100 |          0 |
| 2019FEB | Project B |  2400 |        -10 |
+---------+-----------+-------+------------+

Model B

| time_id |  project  | budget |
+---------+-----------+--------+
| 2019JAN | Project A |   1100 |
| 2019JAN | Project B |   2400 |
| 2019FEB | Project A |   1000 |
| 2019FEB | Project B |   2500 |
+---------+-----------+--------+

而且我正在寻找一个对象数组,每个对象代表每个月的每个项目的结果,类似于我们用sql连接2个表的方式。但是,我不确定如何为此编写序列化程序和API Viewset。

[
  {
    time_id: "2019JAN",
    project: "Project A",
    sales: "1000",
    adjustment: "10",
    budget: "1100"
  },
  {
    time_id: "2019JAN",
    project: "Project B",
    sales: "2500",
    adjustment: "5",
    budget: "2400"
  },
  {
    time_id: "2019FEB",
    project: "Project A",
    sales: "1100",
    adjustment: "0",
    budget: "1000"
  },
  {
    time_id: "2019FEB",
    project: "Project B",
    sales: "2400",
    adjustment: "-10",
    budget: "2500"
  }
]
django django-rest-framework
1个回答
0
投票

您可以尝试这个

Models.py

class ActualSales(models.Model):
    time_id = models.CharField(max_length=8)
    project = models.CharField(max_length=100)
    actual_sales = models.DecimalField(max_digits=20, decimal_places=3)
    adjustment = models.DecimalField(max_digits=20, decimal_places=3)

    def get_budget(self):
        bugdesale = BudgetSales.objects.filter(time_id=self.time_id)
        if bugdesale.exists():
            return bugdesale.first().budget_sales
        else:
            return None

Serializers.py

class ActualSalesSerializer(serializers.ModelSerializer):
    class Meta:
        model = ActualSales
        fields = ('time_id','project', 'actual_sales', 'adjustment', 'get_budget')
© www.soinside.com 2019 - 2024. All rights reserved.