views:

28

answers:

1

Hi, i'm trying to get model objects instance in another one. And i raise this error :

 Manager isn't accessible via topic instance

Here's my model :

class forum(models.Model):
    # Some attributs

class topic(models.Model):
    # Some attributs

class post(models.Model):
    # Some attributs

    def delete(self):
        forum = self.topic.forum
        super(post, self).delete()
        forum.topic_count = topic.objects.filter(forum = forum).count()

Here's my view :

def test(request, post_id):
    post = topic.objects.get(id = int(topic_id))
    post.delete()

And i get :

post.delete()
forum.topic_count = topic.objects.filter(forum = forum).count()
Manager isn't accessible via topic instances

Hope you will help me. Thanks !

A: 

The error in question is caused when you try to access the Manager of a model through an instance of the model. You have used lower case class names. This makes it hard to say if the error is caused by an instance accessing the Manager or not. Since other scenarios that can cause this error are unknown I am proceeding on the assumption that you have somehow mixed up the topic variable so that you end up pointing to an instance of the topic model instead of the class.

This line is the culprit:

forum.topic_count = topic.objects.filter(forum = forum).count()
#                   ^^^^^

You have to use:

forum.topic_count = Topic.objects.filter(forum = forum).count()
#                   ^^^^^
#                   Model, not instance.

What is going wrong? objects is a Manager available at the class level, not to the instances. See the documentation for retrieving objects for details. Money quote:

Managers are accessible only via model classes, rather than from model instances, to enforce a separation between "table-level" operations and "record-level" operations.

(Emphasis added)

Update

See the comments from @Daniel below. It is a good idea (nay, you MUST :P) to use title case for class names. For instance Topic instead of topic. Your class names cause some confusion whether you are referring to an instance or a class. Since the Manager isn't accessible via <model> instances is very specific I am able to offer a solution.The error may not be so self evident always.

Manoj Govindan
However, `topic` does appear to be the actual model class, and not an instance according to the code he provided.
Daniel DiPaolo
@Daniel: true. And yet the error `Manager isn't accessible via Foo instances` is only possible when you try to access a `Manager` using an instance. See the source code: http://code.djangoproject.com/svn/django/trunk/django/db/models/manager.py
Manoj Govindan
Indeed, perhaps another reason (other than "it's best practice") not to use lowercase letters for class names :) It would appear he's potentially using `topic` as a local instance variable and blowing away the reference to the class.
Daniel DiPaolo