Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django abstract base class with ManyToMany

class Question(models.Model):
    answer_choices = models.ManyToManyField(Answers)

    class Meta:
        abstract = True

class HTMLQuestion(Question):
    question = models.fields.TextField()

class TextQuestion(Question):
    question = models.fields.TextField()

class Quiz(models.Model):
    questions = models.ManyToManyField(Question)

The last line doesn't work. I can't run python manage.py makemigrations without the error "Field defines a relation with model 'Question', which is either not installed, or is abstract."

Is there a way to have a list of Question subclassed instances without having it be of type "Question"? I want to have both types HTMLQuestion and TextQuestions to be in the Quiz.

like image 395
Back2Basics Avatar asked Sep 20 '25 09:09

Back2Basics


1 Answers

The answer I ended up with was to forget working with inheritance in Django and instead to put the type in the Question and then created functions of how to deal with that type in the Question model itself.

class Question(models.Model):
    answer_choices = models.ManyToManyField(Answers)
    question_type = models.fields.TextField() # "htmlquestion", "textquestion"
    
    def how_to_deal_with_type(question_type):
        # code here

class Quiz(models.Model):
    questions = models.ManyToManyField(Question)
like image 55
Back2Basics Avatar answered Sep 22 '25 21:09

Back2Basics