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

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.