Using django how to create a method in a model to return request data

In the following code, I use tyring to create a show_pro method that will show all arguments for the case, which are pro.

I get 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
+3
source share
2 answers

Try:

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

Basically, you need to do a reverse search on ForeignKey relationships, and then filter this to get the associated Argument objects with side='p'.

The function is show_pro selfnot a QuerySet - it refers to the object itself.

+8
source

You can not call self.objects, objects- a member of a class, not an instance field. Think of it this way, it would be advisable:

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')
    ...
+1

Source: https://habr.com/ru/post/1707818/


All Articles