Home > Software design >  Add n number of fields in django model
Add n number of fields in django model

Time:10-08

I want to add unlimited fields in the Django model. Actually, I want my model to look like this, Is it Possible ?

CodePudding user response:

It is possible, but in a somewhat different way: Namely, by creating another model (called Choice, for instance) and letting several Choice objects point to the same Question by using a ForeignKey relationship. This way there can then be arbitrarily many Choices. Django's seven-part tutorial explains precisely how to create such an app. I highly recommend to work through it start to finish: https://docs.djangoproject.com/en/4.1/intro/tutorial01/

CodePudding user response:

It will exactly as picture

in admin panel

admin.py

class AnswersInline(admin.TabularInline):
    model = Answers

class QuestionAdmin(admin.ModelAdmin):
    inlines = [
        AnswersInline
    ]

admin.site.register(Question,QuestionAdmin)

modelpy

class Question(models.Model):
    Username = models.CharField(max_length=50, verbose_name='User Name')
    Question = models.CharField(max_length=50, verbose_name='Question')
    CorrectAnswer = models.CharField(max_length=50, verbose_name='Hidden Answer')

    def __str__(self):
        return f"{self.Question}" 

class Answers(models.Model):
    QuestionId = models.ForeignKey('Question', models.DO_NOTHING)
    Answer = models.CharField(max_length=50, verbose_name='User Name')

    def __str__(self):
        return f"{self.Answer}"
  • Related