I have a query set like this that I need to optimize because I think this query set slows down the website performance. The user_wishlist field is a many-to-many DB relational relationship to an Account model/table. How do I?
product_wishlist_store_list = []
non_paged_products = Product.objects.prefetch_related('user_wishlist').select_related('category').filter(is_available=True).order_by('created_date')
for product in non_paged_products.iterator():
# Get User Wishlist
try:
product_wishlist = product.user_wishlist.filter(id=request.user.id).exists()
if product_wishlist:
product_wishlist_store_list.append(product.id)
except ObjectDoesNotExist:
pass
So when I turn on the log for a DEBUG purpose in Django, I see that there are nearly a thousand (0.000) SELECT queries of INNER JOIN. Does the 0.000 mean there is no hit to the database or is it? Still, seeing a thousand queries like that kind of scary to me -- I feel this code is so inefficient. Is it?
CodePudding user response:
Why not just use simple ORM query here and do a values list at the end, this would reduce your code and query timing by a lot.
product_wishlist_store_list = Product.objects.filter(
is_available=True,
user_wishlist__id=id=request.user.id
).order_by('created_date').distinct().values_list("id", flat=True)
Something like this should work for you.