使用django,如何在模型中创建方法来返回查询数据

时间:2009-05-06 21:31:34

标签: django orm

在下面的代码中,我想创建方法show_pro,它将显示专业案例的所有参数。

我收到此错误:

>>> 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

这是代码:

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

2 个答案:

答案 0 :(得分:8)

尝试:

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

基本上,您需要对ForeignKey关系进行反向查找,然后对其进行过滤以获取具有side='p'的相关Argument对象。

show_pro函数中,self不是QuerySet - 它引用了对象本身。

答案 1 :(得分:1)

您无法调用self.objectsobjects是类成员,而不是实例上的字段。以这种方式思考,这样做是否有意义:

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

不是真的。这就是使用self的功能。

相反,您需要访问实例字段。正如泰森所说:

class Case(models.Model):
    ...
    def show_pro(self):
        return self.argument_set.filter(side='p')
    ...