Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue: Sorting by Rating #58

Closed
MoniPar opened this issue Jun 23, 2023 · 2 comments
Closed

Issue: Sorting by Rating #58

MoniPar opened this issue Jun 23, 2023 · 2 comments
Labels
bug Something isn't working

Comments

@MoniPar
Copy link
Owner

MoniPar commented Jun 23, 2023

Since I added a new model (Review) with a rating field, I have been calculating the ratings gathered from the Review Form and saving them to the Review Table. This meant that in order to be able to sort the products by their rating, I will need to save the average rating in the Product table or find out how to add a sortkey for the average rating.

@MoniPar MoniPar added the bug Something isn't working label Jun 23, 2023
@MoniPar
Copy link
Owner Author

MoniPar commented Jun 26, 2023

I managed to sort the average rating using annotation and the Avg() function on the Review rating field. However, the reviews with no rating are showing up first when sorting is desc and vice versa.

Possible solution: Use the F() to sort null values. https://docs.djangoproject.com/en/4.2/ref/models/expressions/#:~:text=Using%20F()%20to%20sort,ordering%20depends%20on%20your%20database.

@MoniPar
Copy link
Owner Author

MoniPar commented Jun 26, 2023

Solution: In trying to use the nulls_last = True to control the order of the NULL value,

if 'direction' in request.GET:
    direction = request.GET['direction']
     if direction == 'desc':
         sortkey = f'-{sortkey}'
products = products.order_by(sortkey)

was conflicting with the desc(nulls_last=True). Sortkey needed to be placed in the F() with desc(nulls_last=True) and then order the products by the new variable "order_logic".

order_logic = sortkey
if 'direction' in request.GET:
    direction = request.GET['direction']
    if direction == 'desc':
        order_logic = F(sortkey).desc(nulls_last=True)
    else:
        order_logic = F(sortkey).asc(nulls_first=True)
products = products.order_by(order_logic)

Tested all other sorting parameters and seems to be working ok while the reviews with no rating are not showing last in desc and first in asc.

@MoniPar MoniPar closed this as completed Jun 27, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
Status: Done
Development

No branches or pull requests

1 participant