0

I'm doing the same query for 3 tables and then the all together. But I feel that I am consuming a lot of resources that way since they are a bit complex queries, I would like to be able to create a single query for all three tables, is this possible in Django?

I know that in SQLALCHEMY there is something similar:

SQLAlchemy How to joiun several tables by one query

Code:

# Review Dish
recent_dish_review = restaurant.models.DishReview. \
                               objects.filter(user_id__in=id_follows,
                                              created_at__lte=timezone.now(),
                                              created_at__gte=days
                                              ).order_by('-created_at')[:limit]

# Review Restaurant
recent_restaurant_review = restaurant.models.RestaurantReview. \
                               objects.filter(user_id__in=id_follows,
                                              created_at__lte=timezone.now(),
                                              created_at__gte=days
                                              ).order_by('-created_at')[:limit]

# User Like Dish
recent_like_dish = restaurant.models.DishesLikes. \
                               objects.filter(foodie_id__in=id_follows,
                                              created_at__lte=timezone.now(),
                                              created_at__gte=days
                                              ).order_by('-created_at')[:limit]

return list(sorted(chain(recent_restaurant_review, recent_dish_review, recent_like_dish))
Carlos Azuaje
  • 109
  • 3
  • 13

1 Answers1

1

Use zip method of python.

single_queryset = zip(recent_restaurant_review, recent_dish_review, recent_like_dish)
return single_queryset

Note: All queryset should have same count of objects in each.

You can iterate zip queryset like below:

form restaurant, dish, like in single_queryset:
    print restaurant, dish, like 
Neeraj Kumar
  • 3,851
  • 2
  • 19
  • 41