Removing duplicates due to order by fields from a related model

I have 2 different models in the same app

class Book(models.Model):
    title = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(max_length=50)
    description = models.TextField(max_length=500)

class Chapter(models.Model):
book = models.ForeignKey(Book,on_delete=models.CASCADE)
num = models.PositiveIntegerField(verbose_name=“Chapter Number”)
rdate = models.DateTimeField(verbose_name=“Release Date”, default=timezone.now)

What I want to do is get all books ordered by descending of release date rdate What I tried is:

Book.objects.all().order_by(‘-chapter__rdate’).distinct()

Some duplicates were found in result, I only had 2 books added, so only 1 book was duplicated. The result was something like this: Book1, Book2, Book2

I have already seen the note from here, and im using SQLite. By using values(), I won’t be able to call get_absolute_url() and some other methods that I want to call so using values() is out of question.

Next I tried to annotate the Chapter rdate into Book query like thisBook.objects.all().annotate(bdate=ExpressionWrapper(F(‘chapter__rdate’), output_field=DateTimeField())).order_by(‘-bdate’).distinct()

Still ended in the same result. I’m totally lost, please need help. I probably won’t change to PostgreSQL now, but I might use it when I deploy the app, so I want both SQLite version and PostgreSQL version solutions for this if at all possible. SQLite solution is absolutely necessary for me since it’s easy to use in development.

#django

2 Likes1.80 GEEK