user1996479
user1996479

Reputation: 31

django custom model manager throwing error

I am trying to build a model for a django website I am working on, and I have all the fields as you can see in the below reviews model. Now I have read how to implement a custom model manager, and for whatever reason for the line of code: "object = ReviewsManager", django throws an error saying that it is an undefined variable. All the examples I have seen do the exact same thing, but they apparently work just fine, any idea whats going on? To be clear I have imported everything that needs importing already, so I know that isnt the issue. As a side note I should mention I am running django 1.6, in case that matters.

//This is the model itself
class Reviews(models.Model):
    mentor_id = models.IntegerField(default=0, unique=False);
    review_id = models.IntegerField(default=0, unique=False);
    title = models.CharField(max_length=200);
    content = models.CharField(max_length=200);
    stars = models.DecimalField(max_digits=1, decimal_places=1);
    ----> object = ReviewsManager

//Trying to use this manager below
---> class ReviewsManager(models.Manager):    

    def getReviewsByMentorId(self, id):
       r = Reviews.objects.filter(mentor_id=id);
       return r;

Upvotes: 1

Views: 357

Answers (2)

knbk
knbk

Reputation: 53669

There are several issues:

  • You try to use the ReviewsManager class before it is defined. Move your class definition up so it's above your Review class, or move it to a separate file and import that file before using the class.

  • You are not instantiating your manager class. After you've solved the first issue, this will raise another error. Use objects = ReviewsManager() instead.

  • As Prashant said, it should be objects, not object

Upvotes: 3

Prashant Gaur
Prashant Gaur

Reputation: 9828

Please change

----> object = ReviewsManager

to

----> objects = ReviewsManager()        ## you should use objects

Code should be like :

class Reviews(models.Model):
    mentor_id = models.IntegerField(default=0, unique=False);
    review_id = models.IntegerField(default=0, unique=False);
    title = models.CharField(max_length=200);
    content = models.CharField(max_length=200);
    stars = models.DecimalField(max_digits=1, decimal_places=1);
    objects = ReviewsManager()

class ReviewsManager(models.Manager): def getReviewsByMentorId(self, id): r = Reviews.objects.filter(mentor_id=id); return r;

Upvotes: 1

Related Questions