Shashank Agarwal
Shashank Agarwal

Reputation: 2804

Django queryset order filter

I have two model objects and they have a many to many relationship -

class Note(models.Model):
    title = models.CharField(max_length=127)
    body = models.TextField()
    is_deleted = models.BooleanField()

    def __unicode__(self):
        return "{} - {}".format(self.title, self.body)

class Tag(models.Model):
    tag_name = models.CharField(max_length = 100)
    notes = models.ManyToManyField(Note)

I'm trying to order Tag object based on the count of non-deleted Notes. I can use Tag.objects.annotate(notes_count=Count('notes')).order_by('-notes_count') to order by count of notes, but this count includes notes that have deleted flag as true. My question is, how can I run this to order Tags by count of non-deleted notes (i.e. note.is_deleted=False)?

I tried defining a method in Tag that returns non-deleted notes only, i.e. -

def non_deleted_notes(self):
    return self.notes.filter(is_deleted=False)

And then replacing Count('notes') with Count('non_deleted_notes'), but that results in an error.

Upvotes: 2

Views: 232

Answers (1)

second
second

Reputation: 28637

i don't think this is supported by the queryset api, so you may need to resort to .extra()

Upvotes: 1

Related Questions