tags:

views:

19

answers:

1

Hello, 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()
...
Attribute error Manager object have no attribute getLastNews

Where I did a mistake? Thx for any help. BTW this is good way to getting info from model and pass to view?

+6  A: 

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.

Ned Batchelder
Ok i have added it and now it's working perfectly. And I have also mistake in getLastNews it should be self.order_by etc without the objects. Thx for help
Artur
It should also be noted that you should follow django's standard conventions as much as possible. For instance, you could just call the method "latest" instead of "getLastNews". You should also implement this by adding a `created_on` field to your news element and filtering by that instead of the id - since it might be nice for someone to create a new article in the past? See this project of mine for an example: http://github.com/monokrome/django-news/blob/master/news/models.py
monokrome