Search code examples
djangodjango-modelsdjango-database

Django - What is the best way to store in the DB answers that can be numerical or text?


I'm working on a student survey project. The model that stores the questions is something like:

ID     Question                 Type 
1      is good teacher?         Choice 
2      What do you like about   Open-answer
       the teacher?

Then in the choice type questions the student will choose an option (e.g.: fully agree) and this will store a numerical code (e.g. 5). But in the open-answer questions , the student will write text.

what kind of field should store these answers in the answers model? maybe TextField?


Solution

  • You ur choices as text if you want to use same column to open text... so instead of set 1,2,3,4 you can write a fixed text when user select the options, so this make your data more readeble

    ANSWER = (
        ("Yes", "Yes"),
        ("No", "No"),
        ("Neutral", "Neutral"),
    )
    

    Or make 2 more columns... one to set type of question (select or text) and the other to store the options (that way you can setup as foreign key and instead of use static values this can be loaded from one model)

    ID     Question                 Type             Answer-Text         AnswerID 
    1      is good teacher?         Choice           null                1
    2      What do you like about   Open-answer      "The way he swag"   null
           the teacher?
    

    Or mix everything with String... but you will have some troubles getting this integer ids... will throw some erros when you try to get it as integer int("1") Will work but int("The way he swag") will raise a error