Opened 6 years ago

Closed 6 years ago

Last modified 6 years ago

#29579 closed Bug (invalid)

Objects count after Many to many related query shows wrong

Reported by: noufalvlpr Owned by: nobody
Component: Database layer (models, ORM) Version: 2.0
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by noufalvlpr)

class Standard(models.Model):
    name = models.CharField(max_length=30)
    created_at = models.DateField(null=True, blank=True)


class Product(models.Model):
    name = models.CharField(max_length=30, null=True)
    standards = models.ManyToManyField(Standard, related_name='products')

created standards with created_at=Null, added some standards to product and after

Product.objects.count()  # 6
Product.objects.filter(standards__created_at__isnull=True).count()  # 7

Change History (4)

comment:1 by noufalvlpr, 6 years ago

Description: modified (diff)

comment:2 by Carlton Gibson, 6 years ago

Resolution: needsinfo
Status: newclosed

Hi.

created standards with created_at=Null, added some standards to product and after

This is too vague to allow us to reproduce the issue.

Can you please provide the exact steps needed to recreate to issue, preferably in a test case or script.

This is core ORM behaviour: it's highly unlikely to be a bug. It's possible of course but, it's much more likely to be something in you code, which you've not specified here.

If you can provide a reproduce example we can investigate.

comment:3 by noufalvlpr, 6 years ago

I am afraid may be its my mistake ..

Steps to reproduce this issue

s1 = Standard.objects.create(name='standard1')
s2 = Standard.objects.create(name='standard2')
p1 = Product.objects.create(name='product1')
p1.standards.add(s1)
p1.standards.add(s2)

Product.objects.count() # 1
Product.objects.filter(standards__created_at__isnull=True).count() # 2

comment:4 by Tim Graham, 6 years ago

Resolution: needsinfoinvalid

To get the correct count, you need to use QuerySet.distinct() since the query is joined to a many-to-many table.

Note: See TracTickets for help on using tickets.
Back to Top