Hello
I have a number of elements that can be of one or more types.
class Type(models.Model):
name = models.CharField(max_length=128, unique=True)
class Element(models.Model):
name = models.CharField(max_length=128, unique=True)
type = models.ManyToManyField('Type')
Let's say that I have 3 types and 3 elements:
In [3]: Type.objects.all()
Out[3]: [<Type: His Type>, <Type: My Type>, <Type: Your Type>]
In [4]: [(e,e.type.all()) for e in Element.objects.all()]
Out[4]:
[(<Element: First Element>, [<Type: My Type>]),
(<Element: Second Element>, [<Type: Your Type>]),
(<Element: Third Element>,
[<Type: My Type>, <Type: Your Type>, <Type: His Type>])]
I'm trying to get a queryset with the elements that are only of the type "My Type"
My idea was to get the elements of this type and check that they are only of one type.
But for some reason it thinks that "Third Element" is of only one type
In [5]: my_type=Type.objects.get(name='My Type')
In [6]: my_type.element_set.annotate(num_types=Count('type')).filter(num_types__exact=1)
Out[6]: [<Element: First Element>, <Element: Third Element>]
In [7]: [(e,e.num_types) for e in my_type.element_set.annotate(num_types=Count('type'))]
Out[7]: [(<Element: First Element>, 1), (<Element: Third Element>, 1)]
when it is of three types
In [8]: Element.objects.get(name='Third Element').type.count()
Out[8]: 3
What I'm doing wrong?