Home > database >  How to iterate through queryset and get value Django
How to iterate through queryset and get value Django

Time:03-16

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]

CodePudding user response:

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.

  • Related