0

I am trying to get the list of count of a field based on date so I can plot stacked bar graph on frontend. These are my models:


class BaseModel(models.Model):
    id: int
    created_at = models.DateTimeField(verbose_name="Created", auto_now_add=True)
    updated_at = models.DateTimeField(verbose_name="Last Updated", auto_now=True)

    class Meta:
        abstract = True

class A(BaseModel):

    name = models.CharField(max_length=512, null=True, blank=True)


class B(BaseModel):
    a = models.ForeignKey(A, on_delete=models.CASCADE)


class C(BaseModel):
    b = models.ForeignKey(B, on_delete=models.CASCADE)

I am trying to get the count (as list) of B and C when getting the list of A for last 7 days. But I am getting count instead not an object.

Using recharts on frontend, my desired output format will be (using sample data from internet):


{
  "items": [
    {
      "name": "android app",
      "chart_data": [
        {
          "name": "A",
          "x": 12,
          "y": 23,
          "z": 122
        },
        {
          "name": "B",
          "x": 22,
          "y": 3,
          "z": 73
        },
        {
          "name": "C",
          "x": 13,
          "y": 15,
          "z": 32
        }
      ]
    },
    {
      "name": "My",
      "chart_data": [
        {
          "name": "A",
          "x": 12,
          "y": 23,
          "z": 122
        },
        {
          "name": "B",
          "x": 22,
          "y": 3,
          "z": 73
        },
        {
          "name": "C",
          "x": 13,
          "y": 15,
          "z": 32
        }
      ]
    }
  ]
}
Nalin Dobhal
  • 2,292
  • 2
  • 10
  • 20
  • this is what you need https://docs.djangoproject.com/en/4.0/topics/db/aggregation/#generating-aggregates-for-each-item-in-a-queryset – Anentropic Dec 14 '21 at 12:47
  • @Anentropic I know about the aggregation but I am not able to get my desired output in this case. – Nalin Dobhal Dec 14 '21 at 14:57
  • you won't be able to go directly to your desired output format from a Django ORM query, you will have to first fetch the data then reshape it to your desired format – Anentropic Dec 15 '21 at 13:57

0 Answers0