Click here to Skip to main content
15,668,691 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hey guys,

I am developing a Django website and I have the following models (simplified):

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    opinions = JSONField(default=default_opinions)

class Author(models.Model):
    name = models.CharField(max_length=50, unique=True)

class Book(models.Model):
    author = models.ForeignKey(Author, on_delete=models.CASCADE, default='0')

with the opinions field being the opinion that a specific user has of the different authors.

   Shakespeare: 0.5,
   Voltaire: 0.6

Then I have a listView BookListView, in which I want to query the Book database, and order them by the opinion the currently logged in user has of their author. In the previous example it would be all the Voltaire's books first, then the Shakespeare's ones.

So I came up with this in my listView:

def get_queryset(self):
    user_opinions = self.request.user.profile.opinions
    queryset = Book.objects.order_by(user_opinions[F("author__name")])
    return queryset

The problem is the F value is computed after the get_queryset(), so I get a F("author__name") key does not exist error.

I thought about iterating through the dict keys and values but I don't see how that could work since opinions are floats (and thus can take any values).

Thanks in advance ^^

What I have tried:

On top of what's above, I have tried using
, but I could not solve my problem that way.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900