Search code examples
pythondjangodjango-modelsdjango-viewsdjango-custom-manager

Django: Custom function value not showing


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?


Solution

  • 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