开发者

Django manager attribute error

开发者 https://www.devze.com 2023-01-17 20:46 出处:网络
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

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

精彩评论

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