Reputation: 2804
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