Manager unavailable with instances of `Model`

I have a polymorphic tag model and I want to create a tag_cloud for it, but when I want to count the related object with tags

tags = TaggedItem.objects.all() # Calculate tag, min and max counts. min_count = max_count = tags[0].object.objects.count() 

I get:

 Manager isn't accessible via Artcle instances 

tagging.models.py

 class Tag(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(unique=True, max_length=100) #..... class TaggedItem(models.Model): tag = models.ForeignKey(Tag) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() object = generic.GenericForeignKey('content_type', 'object_id') #..... 
+4
source share
3 answers

The error was released in the first place, because if I want to access tags and count them in this situation, I rather want to change

 tags = TaggedItem.objects.all() # Calculate tag min and max counts. min_count = max_count = tags[0].object.objects.count() 

in

 tags = Tag.objects.all() # Calculate tag, min and max counts. min_count = max_count = tags[0].taggeditem_set.count() 
+3
source

You are trying to access the manager from a model instance that is not possible. Additional Information: Retrieving objects (especially Note).

  tags[0].object.objects.count() \/ ¨¨¨¨¨¨ /\ 

rather you can do it (not verified):

 object_klass = tags[0].object.__class__ min_count = max_count = object_klass.objects.filter(pk=tags[0].object.pk).count() 
+5
source

It would not be easier / cleaner to just add a counting method to the TaggedItem. Perhaps something like below. I'm a little rusty, this code may not work.

 class TaggedItem(models.Model): tag = models.ForeignKey(Tag) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() object = generic.GenericForeignKey('content_type', 'object_id') def get_object_count(): return self.object__count #or return self.object.count() 
+4
source

Source: https://habr.com/ru/post/1346704/


All Articles