I'm working on my first django project that involves a student gradebook. Starting small, I'm just working on an app where teachers can upload students (student information - name and email address) and organize them into courses. My models so far are:
class Course(models.Model):
course_name = models.CharField(max_length=20, default='Course')
def __unicode__(self):
return self.course_name
class Student(models.Model):
course = models.ForeignKey(Course)
name_text = models.CharField(max_length=40, default='First Last')
email_address = models.EmailField(max_length=40, default='address@address.com')
def __unicode__(self):
return self.name_text
However, I'm not sure if the Course class is needed. I didn't think much of it, until I tried to create my first form where a user adds a student to the database. I had tried:
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields= ('name_text',)
But this didn't work. I would get an error saying that the course field could not be null (null value in column "course_id" violates not-null constraint). So I modified to: fields ('course', 'name_text,). That worked.
This is what got me wondering if the Course class would actually be necessary. Ultimately I would like to be able to upload a text file with student names, parse the text to get the names (and email addresses) and create instances of the students. Only then would I assign the students to a course. But I get the feeling that the way I have my model setup right now will always insist that the student is assigned a course.
Should the class Course be kept?
If there is a 1-n relationship by student-course (many students in one course, a student in only one course) it's completely right.
Having a CharField instead that saves the course_name
would eventually lead to inconsistencies (see db normalization, too), e.g. start off like this:
name_text | course_name
-----------------------
chris | cs-101
doug | cs-101
now cs-101 is renamed to cs-101-old and cs-101 is a new course with different topics. The db however still says we are both in new "new" course. If you have a ForeignKey
to Courses
you just change one value and the values in the students table change as well, since they are just pointers.
If you want the course to be optional just add a null=True
to your ForeignKey declaration.
course = ForeignKey(Courses, null=True)