1

I'm trying to sort a query according to a foreign key field case insensitive. My models are:

class Post(models.Model):
title = models.CharField(max_length = 80)
author = models.ForeignKey(User, default = User)
trade_option = models.CharField(max_length= 10)

class Book(models.Model):
book_title = models.CharField(max_length = 60)
post = models.ForeignKey(Post)

I want to sort my post objects according to the book_title field case insensitive.

I know if I want to sort case insensitive with the fields in Class Post I can just do:

posts = Post.objects.filter(trade_option= 'buy').extra(select = 
    {'lower_name' : 'lower( title )'}).order_by('lower_name')

However, when I try the same technique with sorting with foreign key book with book_title:

posts = Post.objects.filter(trade_option= 'buy').extra(select = 
    {'lower_name' : 'lower( book__book_title )'}).order_by('lower_name')

I get the error "no such column: book__boot_title"

I would like to know where I'm doing this wrong. Thanks

2 Answers 2

1

I had the same problem. Here's what you should do:

from django.db.models.functions import Lower

posts = Post.objects.filter(trade_option= 'buy').order_by(Lower('title'))
Sign up to request clarification or add additional context in comments.

1 Comment

Good answer, but keep in mind this is new in Django 1.8
0

A related lookup like book__book_title only works in the context of Django. Anything in extra is not processed by Django, so these lookups won't work. You have to explicitly fetch the result from the related table.

Please note that the ordering you're trying to define is most likely not what you expect it to be: a Post object can have multiple related Book objects. Ordering by book__book_title (manually or through the orm) can give you either an indeterminate ordering or duplicate rows, depending on the exact details of your query. You need to define which related book_title the posts should be ordered by.

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.