How to run a raw query using a dynamic field model in Django 1.9?

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

See stack overflow.squite

The expected result is a table with several columns.

The first column heading is simple Product, and the other column headings are store names.

Values ​​are simply product names and aggregated product sales values ​​in these stores.

Which stores will be shown completely dynamically. Maximum should be 9 stores.

enter image description here

The same in text format:

Save 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    |
|--------------------------------------|

Relationship:

  • Sales owned by the store.
  • Sales owned by Product
  • The store has a lot of sales.
  • The product has a lot of sales.

What i want to achieve

:

S1-S3:

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

, 2 Python?

:

, , ?

, Django .

, , ?

, ?

, postgresql, ?

+4

Source: https://habr.com/ru/post/1648909/


All Articles