开发者

Django manager attribute error

I have a problem to add custom methods to my models. I found solution in django book but it does not work. Here is my code for models

class NewsManager(models.Manager):
    def getLastNews(self):
        return self.objects.order_by('-id')[:3]

class News(models.Model):
    title=models.SlugField()
    shortBody=models.CharField(max_length=250)
    fullBody=models.TextField()
    author=models.ForeignKey(User)

And now I run python manage.py shell and type

from news.models import *
News.objects.getLastNews()
...
开发者_如何学GoAttribute error Manager object have no attribute getLastNews

Where I did a mistake?

BTW is this a good way of getting info from model and passing it to view?


You have to associate the manager with the model:

class News(models.Model):
    # ..fields go here..

    objects = NewsManager()

And yes, this is a good way to add "table-level" functionality to your model.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜