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

Query Expressions support #4

Open
aidsoid opened this issue Jan 31, 2018 · 4 comments
Open

Query Expressions support #4

aidsoid opened this issue Jan 31, 2018 · 4 comments
Assignees

Comments

@aidsoid
Copy link

aidsoid commented Jan 31, 2018

From Django documentation https://docs.djangoproject.com/en/1.11/ref/models/querysets/#order-by

You can also order by query expressions by calling asc() or desc() on the expression:
Entry.objects.order_by(Coalesce('summary', 'headline').desc())

Or another example from documentation https://docs.djangoproject.com/en/1.11/ref/models/expressions/#some-examples

# Expressions can also be used in order_by()
Company.objects.order_by(Length('name').asc())
Company.objects.order_by(Length('name').desc())

But when I try to use code like this:

sort = ['-some_field_name', Length('some_field_name').asc()]
current_obj = SomeModel.objects.get(pk=current_pk)
some_qs = SomeModel.objects.all().order_by(*sort)
prev_obj = prev_in_order(current_obj, qs=some_qs)

I get an error:
'OrderBy' object does not support indexing
in this file https://github.com/gregplaysguitar/django-next-prev/blob/master/next_prev.py in line 49
if field[0] == '-':

Could you please add support of Query Expressions and fix it?

@aidsoid
Copy link
Author

aidsoid commented Jan 31, 2018

Test example:

    def test_custom_with_query_expression(self):
        qs = Post.objects.all().order_by(Length('text').desc())
        first = qs.first()
        self.assertEqual(first, self.post3)

        second = next_in_order(first, qs)
        self.assertEqual(second, self.post1)

@gregplaysguitar
Copy link
Owner

Ok - that's a great suggestion, I haven't got time right now but I'll see what I can do in the next few weeks.

In this case though, could you not just go something like this?

Entry.objects.order_by('-summary', '-headline')

@aidsoid
Copy link
Author

aidsoid commented Feb 1, 2018

Coalesce('summary', 'headline').desc() - it's just an example of "Query Expression" from the documentation. In my case I need to sort by length of text inside a field Length('text').desc(). Thanks for support.

@gregplaysguitar
Copy link
Owner

Ah ok, that makes sense.

@gregplaysguitar gregplaysguitar self-assigned this Feb 1, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants