There are two tables
catalog_product:
ID | Name.
10 PROD3.
9 PROD2.
8 PROD1
11 PROD5
Catalog_Productcategory: (From MPTT Libe, Tree Model)
ID | Name | LFT | RGHT | Tree_ID | Level | Parent_id.
2 ROOT1 1 6 1 0 NULL
3 subroot1 2 5 1 1 2
5 subsubroot1 3 4 1 2 3
6 ROOT2 1 4 2 0 NULL
7 subroot2 2 3 2 1 6
Table Catalog_Product_category:
ID | Product_id | ProductCategory_id.
7 10 2.
8 9 3.
9 8 5.
10 11 7.
Catalog_Productcategory tree looks like this:
root1
Subroot1.
subsubroot1
root2.
Subroot2.
My two models with a connection Many to many
class Productcategory (MPTTMODEL):
"" "categories of products" ""
Name = Models.charfield (max_length = 255)
Parent = TreeForeignKey ('Self', On_delete = Models.cascade, NULL = True, Blank = True, Related_name = 'Children')
Class MPTTMETA:
Order_inSertion_BY = ['name']
DEF __STR __ (SELF):
Return Self.name.
DEF Get_Products (Self):
Return Self.category_Products.all ()
Class Product:
"""Products"""
Name = Models.charfield (max_length = 1024)
Category = Models.ManyTomanyField (ProductCategory, Related_name = "Category_Products")
DEF __STR __ (SELF):
Return Self.name.
I want to receive when contacting Root1 not only products that are in this root category, but all products that are in subsidiary categories, but when accessing a subsidiary, just what is in it.
def getiing (Request):
Categories = ProductCategory.Objects.Prefetch_Related ('Category_Products')
Stores = []
For cat in categories:
Products = [{'product_id': product.id, 'Product_name': Product.name} for product in cat.get_products ()]
If not Products:
Pass
ELSE:
Stores.APPEND ({'category_id': cat.id, 'Category_name': cat.name, 'Products': Products})
Print (* Stores, sep = '\ n')
Now I get it:
{'category_id': 2, 'category_name': 'root1', 'Products': [{'product_id' : 10, 'Product_name': 'PROD3'}]}
and should get something like this:
Root1
Filter
{'category_id': 2, 'category_name': 'root1', 'Products': [{'product_id' : 10, 'Product_name': 'PROD3'}, {'Product_ID': 9, 'Product_name': 'PROD2'}, {'Product_ID': 8, 'Product_Name': 'PROD1'}]}
SUBROOT1 filter
{'category_id': 3, 'category_name': 'Subroot1', 'Products': [{'product_id' : 10, 'Product_name': 'PROD3'}, {'Product_ID': 9, 'Product_Name': 'PROD2'}]}
Categories may be so
root1
subroot1_1
subsubroot1_1_1
subsubsubroot1_1_1_1
subsubroot1_1_2.
Subroot1_2.
SUBSUBROOT1_2_1
root2.
Subroot2_1
Answer 1
In general, only one line of the code does everything that I need. Shock and pain
product.Objects.Filter (
Category__in = Productcategory.Objects.get (id = 5) .Get_Descendants (include_Self = True)
)