4

I have a complex result that requires writing raw sql queries.

See https://stackoverflow.com/a/38548462/80353

The expected result is a table showing several columns.

The first column header is simply Product and the other column headers are store names.

The values are simply the product names and the aggregated sales values of the product in these stores.

Which stores will be shown is entirely dynamic. Maximum should be 9 stores.

enter image description here

The same in text format:

Store table

------------------------------
| id  | code | address       |
|-----|------|---------------|
| 1   | S1   | Kings Row     |
| 2   | S2   | Queens Street |
| 3   | S3   | Jacks Place   |
| 4   | S4   | Diamonds Alley|
| 5   | S5   | Hearts Road   |
------------------------------

Product table

------------------------------
| id  | code | name          |
|-----|------|---------------|
| 1   | P1   | Saucer 12     |
| 2   | P2   | Plate 15      |
| 3   | P3   | Saucer 13     |
| 4   | P4   | Saucer 14     |
| 5   | P5   | Plate 16      |
|  and many more ....        |
|1000 |P1000 | Bowl 25       |
|----------------------------|

Sales table

----------------------------------------
| id  | product_id | store_id | amount |
|-----|------------|----------|--------|
| 1   | 1          | 1        |7.05    |
| 2   | 1          | 2        |9.00    |
| 3   | 2          | 3        |1.00    |
| 4   | 2          | 3        |1.00    |
| 5   | 2          | 5        |1.00    |
|  and many more ....                  |
| 1000| 20         | 4        |1.00    |
|--------------------------------------|

The relationships are:

  1. Sales belongs to Store
  2. Sales belongs to Product
  3. Store has many Sales
  4. Product has many Sales

What I want to achieve

I want to display by pagination in the following manner:

Given the stores S1-S3:

-------------------------
| product | S1 | S2 | S3 |
|---------|----|----|----|
|Saucer 12|7.05|9   | 0  |
|Plate 15 |0   |0   | 2  |
|  and many more ....    |
|------------------------|

For more details of the schema, check the question in How to get back aggregate values across 2 dimensions using Python Cubes?

My question

The schema is not super important to my question which is:

Since I am going to write a complex raw query, is there a way to map the query result to a model where the fields are dynamic?

I found documentation about how to execute raw queries in Django and how to execute raw queries to existing models with fixed fields and matching table.

My question is is it possible to do that for a model that has no matching table and dynamic fields?

If so, how?

Or if I choose to use materialised view in postgresql, how do I match it with a model class?

Community
  • 1
  • 1
Kim Stacks
  • 10,202
  • 35
  • 151
  • 282

0 Answers0