0

Trying to understand how to make custom functions in Django. I have the following:

models:

class OptionManager(models.Manager):
    def test(self):
        test = "test"
        return test

class Option(models.Model):
    value = models.CharField(max_length=200)
    objects = OptionManager()
    def __str__(self):
        return self.value

view:

def questn(request, question_id):
    o = Option.objects.filter(question=question_id).annotate(num_votes=Count('answer'))
    return render(request, 'test.html', {'o':o})

test.html

{{ o.test }}

My page is blank, but it should display "test". What am I doing wrong?

tshepang
  • 12,111
  • 21
  • 91
  • 136
thedeepfield
  • 6,138
  • 25
  • 72
  • 107

1 Answers1

2

The reason it is not working is, the custom method should not be on manager, but on the model itself

class Option(models.Model):
    value = models.CharField(max_length=200)
    objects = OptionManager()
    def __str__(self):
        return self.value

    def test(self):
        test = "test"
        return test

Now, for what you are looking to do, it should be

{{ o.objects.test }}

Please note that this is the wrong usage of custom methods. Managers are normally used for custom filtering options.

Read more on the managers here

karthikr
  • 97,368
  • 26
  • 197
  • 188