[Answer]-Can't add new function to models/table class in django (python)

1đź‘Ť

âś…

you are almost there

you need to add the def __str__() method inside of the Question class inside of models.py file like.

your models.py should look like this:

from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def __str__(self):
        return self.question_text
class Choice(models.Model):
    question = models.ForeignKey(Question)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __str__(self):
        return self.choice_text #or whatever u want here, i just guessed u wanted choice text

what you are actually doing is overriding a built in dunder method in a class you are subclassing. models.Model itself has a __str__ method inside it already, and you are just modifying its behavior in your Question version of models.Model

PS. the method name should be __unicode__ instead of __str__ if you are on python 2

PPS. a little bit of OOP language: if a “function” is part of a class, it is called a “method”

👤TehTris

Leave a comment