I have a relation between category, subcategory, and sub child category, and product
is related to sub child category
, but I want to display the list of subcategory
products. Please let me know how I can do it.
here is my models.py
file...
class Category(models.Model):
cat_name=models.CharField(max_length=225)
cat_slug=models.SlugField(max_length=225, unique=True)
class SubCategory(models.Model):
subcat_name=models.CharField(max_length=225)
subcat_slug=models.SlugField(max_length=225, unique=True)
category = models.ForeignKey('Category', related_name='subcategoryies', on_delete=models.CASCADE, blank=True, null=True)
class SubChildCategory(models.Model):
subcategory=models.ForeignKey(SubCategory, related_name='SubChildRelated', on_delete=models.CASCADE, default=None, verbose_name='Sub Category')
name=models.CharField(max_length=50, default=None)
slug=models.SlugField(unique=True, max_length=50)
here is my product models.py
file...
class Product(models.Model):
name=models.CharField(max_length=225)
slug=models.SlugField(max_length=225, unique=True)
subcategory=models.ManyToManyField(SubChildCategory, related_name='pro_subchild', verbose_name='Select Category')
here is my views.py
file, where I am trying to display the SubCategory
product...
def home(request):
subcat_product = Product.objects.prefetch_related('subcategory')
return render(request, 'frontend/index.html',{'subcat_product':subcat_product}
but the above function is displaying all the products which are available in SubChildCategory
, I want to display products according to the SubCategory
on my homepage.
Please let me know what is the process to display these products.
I think it should work:
# You can also get your sub category by id
sub_child_categories = SubCategory.objects.get(
slug=your_sub_category_slug
).SubChildRelated.all()
subcat_products = Product.object.none()
for sub_child_category in sub_child_categories:
subcat_products |= sub_child_category.pro_subchild.all()
subcat_products
is all the products that the a SubCategory
has.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.