Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Taking three records from the products in the table according to their categories

I have two tables named categories and products. How can I get three records from each category on the homepage? Thanks in advance

class Category(models.Model):
    name = ...

class Produc(models.Model):
    name = ...
    category = models.ForeignKey(Category, ...

class Home_Cls(TemplateView):
    ...

    def homepro(self):
        cats = Category.objects.all()
        for cat in cats :
            que= Products.objects.filter(
                category_id=cat[..]
            ).order_by('?')[:3]

        return que

I tried a little. 🙁 Waiting for your help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can try this way by storing in list and returning that list:

class Home_Cls(TemplateView):
    ...

    def homepro(self):
        cats = Category.objects.all()
        que_lst = []
        for cat in cats :
            que_lst.extend(list(Products.objects.filter(category_id=cat[..]).order_by('?')[:3]))

        return que_lst
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading