我想做一個基于用戶添加的動物的簡單推薦系統。我只想顯示某個類別的產品,該類別已在“zwierzeta”字典中映射。所以基本上,如果用戶選擇了他有一匹馬(即 id 1,我只想顯示具有類別 4 的產品)另外,如果用戶有超過 1 只動物,我想從類別 id 串列中隨機顯示它們。邏輯似乎很好,我只是 django 的新手,我不知道如何實際遍歷查詢集以及如何從特定查詢集中獲取值(動物)。get 方法不起作用。您知道如何從查詢集中獲取特定值嗎?
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]
uj5u.com熱心網友回復:
您可以將其簡化為:
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]
但是使用帶有硬編碼專案的字典看起來很奇怪:這意味著您需要提前知道主鍵,并且以后很難添加新類別,因為它需要部署新的軟體版本。將類別和動物之間的關系建模為一個ManyToManyField或等價物可能會更好。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/444393.html
