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

How to iterate through queryset and get value Django

I wanna do a simple recommendation system based on users’ Animals that they added. I want to show only products of a category, that’s been mapped in "zwierzeta" dictionary. So basically if user has chosen that he has a horse (which is id 1, i want to show only products that have category 4) Also if user has more than 1 animals, i want to show them randomly from list of categories id. The logic seems to be fine, im just new at django and i have no idea how to actually iterate through the querysets and how to get a value(animal) from a particular queryset. The get method doesnt work. Do you have any idea how to get a particular value from a queryset?

class MyAnimal(models.Model):
    name = models.CharField(max_length=256)
    animal = models.ForeignKey(Animal, on_delete=models.CASCADE, null=False)

class ProductInStore(models.Model):
    product = models.ForeignKey('Product', on_delete=models.CASCADE)

class Product(models.Model):
    product_category = models.ManyToManyField(EcommerceProductCategory)

def list(self, request):    
    zwierzeta = {1 : 4, 6: 5, 8: 6, 9: 6, 4: 3}
    
    qs = MyAnimal.objects.filter(user=self.request.user)
    #checking if there is an animal with user == self.request.user
    if qs:
        
        if len(qs)==1:
            # if user has only 1 animal, get that animals race and if compare it with the dictionary to get product__product_category
            animal = qs.get('anmial')
            qs_value = zwierzeta[animal]
            return ProductInStore.objects.filter(product__product_category=qs_value)[:1]
        
        elif len(qs)>1:
            # if user has more than 1 animal, iterate through all the animals, get all the individual category id for that specific animal and append it
            list_of_categories = []
            for querysets in qs:
                category_id = querysets.get('animal')
                value = zwierzeta[category_id]
                list_of_categories.append(value)
            return ProductInStore.objects.filter(product__product_category=random.choice(list_of_categories))
        
        return ProductInStore.objects.all().order_by('?')[:1]
    
    return ProductInStore.objects.all().order_by('?')[:1]

>Solution :

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

You can simplify this to:

def list(self, request):    
    zwierzeta = {1 : 4, 6: 5, 8: 6, 9: 6, 4: 3}
    qs = MyAnimal.objects.filter(user=self.request.user)
    if qs:
        category=random.choice([zwierzeta[q.animal_id] for q in qs])
        result = ProductInStore.objects.filter(
            product__product_category__id=category
        )
    else:
        result = ProductInStore.objects.all()
    return result.order_by('?')[:1]

But using a dictionary with hardcoded items looks odd: it means you need to know the primary keys in advance and it is hard to later add new categories since it requires deploying a new software version. It might be better to model the relation between a category and an animal as a ManyToManyField or equivalent.

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