Question about using a model as a member in another model.

35 views
Skip to first unread message

Pemby

unread,
Dec 17, 2015, 3:19:52 PM12/17/15
to Django users
Hi all,

This is totally a beginner question and if this is the incorrect forum for this type of question please let me know!

So I have a couple questions.
First I have two models

a Student (as a signup)
a Class (as a Elective)

What is the correct way to associate nth amount of students to a class?
Also after I associate a list / dict (or whatever we decide here), would adding logic as a max limit of students be added to my Elective controller class? Or would the logic of "Max students" in a Elective instance be better contained in m elective class?
Would I use a constructor with methods in my model to check?

here are the models for contex (still in progress)

# Create your models here.

class SignUp(models.Model):
first = models.CharField(max_length=25, null=True, blank=False)
last = models.CharField(max_length=25, null=True, blank=False)
studentID = models.CharField(max_length=6, null=True, blank=False)
gradeChoice = models.CharField(max_length=2, choices=grd, default='1')
genChoice = models.CharField(max_length=2, choices=gender, default='1')
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
update = models.DateTimeField(auto_now_add=False, auto_now=True)

def __unicode__(self):
return smart_unicode('Student: ' + self.last + ', ' + self.first)


class Elective(models.Model):
title = models.CharField(max_length=25, null=True, blank=False)
description = models.CharField(max_length=500,null=True, blank=False)
tFname = models.CharField(max_length=25, null=True, blank=False)
tLname = models.CharField(max_length=25, null=True, blank=False)

def __unicode__(self):
return smart_unicode('Class Name:: ' + self.title)


Please let me know of you have any questions.

Eliot

unread,
Dec 18, 2015, 12:00:44 PM12/18/15
to Django users
It looks like you need a ForeignKey relationship.

So your SignUp model would have an extra field, looking something like this:

class SignUp(models.Model):
   
#...other fields...
   elective
= models.ForeignKey(Elective)

Now each SignUp instance is related to a particular Elective.  And any Elective instance can have multiple SignUps.

# Get all sign ups for the elective "myElective"
signups = myElective.signup_set.all()

Reply all
Reply to author
Forward
0 new messages