Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manager isn't accessible via `Model` instances

I have polymorphic tagging model and I want to create tag_cloud for it, but when I wanna count related object to 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')
    #.....
like image 693
Alireza Savand Avatar asked Dec 13 '22 14:12

Alireza Savand


2 Answers

Your are trying to access the manager from a model instance which is not possible. More infos:Retrieving objects (specially the Note).

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

rather you can do this (not tested):

object_klass = tags[0].object.__class__
min_count = max_count = object_klass.objects.filter(pk=tags[0].object.pk).count()
like image 82
manji Avatar answered Dec 27 '22 18:12

manji


Would it not be easier/cleaner to just add a count method to TaggedItem. Possibly something like below. I'm a bit rusty this code might 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()
like image 31
solartic Avatar answered Dec 27 '22 16:12

solartic