Rohit Chopra Rohit Chopra - 1 month ago 5x
Python Question

django:adding more than one value in model field

i want to create a app for classroom in which their only one teacher and students can be more than one. i want to store usernames of students in one classroom. is there any model field i can use to store usernames of students.
my code so far:

from django.db import models
from django.conf import settings
# Create your models here.

class classroom(models.Model):
teacher = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
students = models.CharField(max_length=120)


You should create a separate model for storing students, but even more than that - you should really start with the Django tutorial on their official site.

But your problem is solved accordingly:

from django.db import models
from django.conf import settings

class ClassRoom(models.Model):
    teacher = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)

class Student(models.Model):
    name = models.CharField(max_length=128)
    class_room = models.ForeignKey(ClassRoom)

This way you can add as many students as you like. This is the standard practice, but if you really want to just save the names and NOTHING else (and are using PostgreSQL), you can also use the ArrayField for that. But check it out in the documentation yourself.