modbender
modbender

Reputation: 419

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 this Book.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.

Upvotes: 0

Views: 131

Answers (3)

modbender
modbender

Reputation: 419

Worked after I tried this :

Book.objects.all().annotate(ch_date=Max('chapter__rdate')).order_by('-ch_date')

Thanks for all the help.

Upvotes: 0

vikasvmads
vikasvmads

Reputation: 552

You should try like below:

Book.objects.all().order_by('-chapter__rdate').distinct('chapter__rdate')

This will give you a different chapter_rdate.

Upvotes: 1

shafikshaon
shafikshaon

Reputation: 6404

You can try this

Chapter.objects.values('book__title').distinct()

This will return books which have at least one chapter.

Upvotes: 1

Related Questions