tags:

views:

430

answers:

2

In the following code, I'm tyring to create the method show_pro that will show all Arguments for the Case that are pro.

I am getting this error:

>>> Case.objects.all()[0].show_pro()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/john/mysite/../mysite/cases/models.py", line 23, in show_pro
    return self.objects.filter(argument__side__contains='p')
  File "/usr/lib/python2.5/site-packages/django/db/models/manager.py", line 151, in __get__
    raise AttributeError, "Manager isn't accessible via %s instances" % type.__name__
AttributeError: Manager isn't accessible via Case instances

here is the code:

from django.db import models
from django.contrib.auth.models import User
import datetime

SIDE_CHOICES = (
        ('p', 'pro'),
        ('c', 'con'),
        ('u', 'undecided'),
    )



    class Case(models.Model):
        question = models.CharField(max_length=200)
        owner = models.ForeignKey(User)
        pub_date = models.DateTimeField('date published')
        rating = models.IntegerField()
        def __unicode__(self):
            return self.question
        def was_published_today(self):
            return self.put_date.date() == datetime.date.today()
        def show_pro(self):
            return self.objects.filter(argument__side__contains='p')

    class Argument(models.Model):
        case = models.ForeignKey(Case)
        reason = models.CharField(max_length=200)
        rating = models.IntegerField()
        owner = models.ForeignKey(User)
        side = models.CharField(max_length=1, choices=SIDE_CHOICES)
        def __unicode__(self):
            return self.reason
+4  A: 

Try:

def show_pro(self):
    return self.argument_set.filter(side='p')

Basically, you need to do a reverse lookup on the ForeignKey relationship and then filter that to get the related Argument objects that have side='p'.

In the show_pro function, self is not a QuerySet—it refers to the object itself.

Tyson
self refers to Case right? I can do Case.objects from outside the class why not self.objects inside?
Johnd
+1  A: 

You can't call self.objects, objects is a class member, not an field on the instance. THink about it this way, would it make sense to do:

c0 = Case.objects.all()[0]
c1 = c0.objects.all()[1]

Not really. That's what using self does.

Instead, you need to access the instance fields. As Tyson suggested:

class Case(models.Model):
    ...
    def show_pro(self):
        return self.argument_set.filter(side='p')
    ...
tghw
wow, looks like I need to brush up on Python or my OO skills. Why can't I call a class member (that is callable) from within a the class?
Johnd