【问题标题】:Django filter query from many to many fieldsDjango从多到多字段过滤查询
【发布时间】:2019-01-29 18:25:22
【问题描述】:

models.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)

views.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]
    },

我需要对 items 进行更合适的查询,其中关键字是来自 keyword 模型的名称,查询参数为“Burger”作为关键字 我的网址就像 http://127.0.0.1:8000/api/foodfeeds/?keywords=BURGER,teste&mood=happy&location=2323,7767.323&price=2

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

【问题讨论】:

    标签: python django django-models django-rest-framework django-views


    【解决方案1】:

    像这样进行过滤:

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

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

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

    【讨论】:

      【解决方案2】:

      不是 100% 确定我是否正确理解了您的问题。在这里,我在列表中使用了带有关键字的 for 循环,将每个关键字实体添加到列表中 - 按名称选择。

      class FoodfeedList(APIView):
      def get(self,request,format=None):
          keywords = request.GET['keywords'].split(",")
          mood=request.GET['mood']
          location=request.GET['location'].split(",")
          price=request.GET['price']
          user_id=request.user.id
          keyword_names = []
      
          for keyword in keywords:
              keyword_names += Item.objects.get(name=keyword)
      
          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']
              json['keywords'] = keyword_names
              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)
      

      【讨论】:

      • 我需要像 items=ItemVariation.objects.filter(keywords = keywords[0]) 这样的过滤查询,但我的问题是我不能在多对多字段中使用关键字字符串
      • 您可能会使用这种方法执行数百个查询,如果您使用连接,您可以在单个查询中同时获取多个表中的数据 - RDBM 系统就是为此而设计的。 @changak 的回答显示了如何加入
      猜你喜欢
      • 2013-08-18
      • 2018-06-07
      • 2015-07-18
      • 1970-01-01
      • 2017-03-09
      • 2020-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多