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?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.