首页 > 解决方案 > Django从多到多字段过滤查询

问题描述

模型.py

class Keyword(models.Model):
        name=models.CharField(max_length=500,unique=True)
        image = models.ImageField(upload_to='keywords/', blank=True, null=True)
        mood=models.ManyToManyField(Mood,blank=True)
        def __str__(self):
            return str(self.name)

    class ItemVariation(models.Model):
        restaurant=models.ForeignKey(Restaurant,on_delete=models.CASCADE)
        items_id=models.ForeignKey(Item,on_delete=models.CASCADE)
        price=models.IntegerField(blank=True,null=True,default=0)
        item_code=models.CharField(max_length=500)
        keywords= models.ManyToManyField(Keyword)
        image=models.ImageField(upload_to='dishes/', blank=True, null=True)
        def __str__(self):
            return str(self.id)

视图.py

class FoodfeedList(APIView):
    def get(self,request,format=None):
        keyword = request.GET['keywords'].split(",")
        mood=request.GET['mood']
        location=request.GET['location'].split(",")
        price=request.GET['price']
        user_id=request.user.id
        items=Item.objects.all()
        item_variation=ItemVariation.objects.all()
        search_restaurant=SearchRestaurant()
        search_result=search_restaurant.searchRes(location[0],location[1],keyword[0],user_id)
        all_results=[]
        json={}
        for i in search_result:
            json={}
            json['res_id'] = i['restaurant']['id']
          # keywords_list = ItemVariation.objects.filter(keywords=keyword[0])

            items=ItemVariation.objects.filter(restaurant = request.user.id)
            itemserializer=ItemVariationSerializer(items,many =True)
            json['itemserializer']=itemserializer.data
            all_results.append(json)
        # items_serilizer=ItemsSerializer(items,many=True)
        return Response(all_results)

输出

"res_id": 2,
"itemserializer": [
    {
        "id": 1,
        "price": 0,
        "item_code": "2134ffsd",
        "image": null,
        "restaurant": 1,
        "items_id": 1,
        "keywords": [1,2,3]
    },

我需要对关键字模型名称的项目进行更合适的查询,查询参数为“汉堡”作为关键字我的网址就像 http://127.0.0.1:8000/api/foodfeeds/?keywords=BURGER,teste&mood=happy&location=2323, 7767.323&价格=2

如果关键字在ItemVariation模型中的多对多字段中匹配,则它应该返回 itemvariation

标签: pythondjangodjango-modelsdjango-rest-frameworkdjango-views

解决方案


像这样进行过滤:

items=ItemVariation.objects.filter(keywords__name__in=keywords)

或为单个关键字执行此操作:

items=ItemVariation.objects.filter(keywords__name=keywords[0])

推荐阅读