0

With Django's ORM, I have a simple Question and Topic model like so:

class Topic(models.Model):
    name = models.CharField(max_length=200)

class Question(models.Model):
    topic_items = models.ManyToManyField(Topic, blank=True)
    date_asked = models.DateField()

Suppose I have four Questions asked each on separate dates, with the fourth sharing two topics 'topic1', 'topic2'

If I do the following query with topics_restrict a list of the two topic ids for 'topic1' and 'topic2'...

q_filter = Question.objects.filter(topic_items__in=topics_restrict).distinct()

Then I get four results (instead of five, which would have resulted without the distinct)

Now if I do the following:

    return q_filter.annotate(
        total=Count('date_asked')
    ).values_list('total', flat=True)

I get the result [2,1,1,1] instead of [1,1,1,1] - ie, as if the distinct() had never been applied.

The only way to get around it is to do...

q_filter = Question.objects.filter(pk__in=q_filter.values_list('pk', flat=True))

... and then annotate on that q_filter.

But there has to be a better way?

Stephen Brown
  • 21
  • 1
  • 2

0 Answers0