1👍
✅
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.
Source:stackexchange.com