Reputation: 131
I have two models: Profile and Course. Profile stores user info. Course has a title, description and date. User can sign up for the course using link. My goal is to make a list of users, who belong to each course.
I tried using ForeignKey, but i need to have user added to the list only after he signs up for it.
class Course(models.Model):
course_title = models.CharField(max_length=200)
course_description = models.TextField()
course_published = models.DateTimeField("date published", default = datetime.now())
course_users = []
def __str__(self):
return self.course_title
def course_signup(request):
# here i guess i need to somehow add the user to the list
Course.course_users.append(Profile.id)
return redirect("main:homepage")
Profile code:
class Profile (models.Model):
user=models.OneToOneField(User, on_delete=models.CASCADE)
image=models.ImageField(default='default.jpg',upload_to='profile_pics')
def __str__(self):
return f'{self.user.username} Profile'
def save(self, *args, **kwargs):
super(Profile,self).save(*args,**kwargs)
img = Image.open(self.image.path)
if img.height > 300 or img.width >300:
output_size = (300,300)
img.thumbnail(output_size)
img.save(self.image.path)
I expect to have a list of users in Course.
Upvotes: 0
Views: 164
Reputation: 10389
That's just a many-to-many (m2m) relationship. You can either use the ManyToMany()
part of Django, or you could create your own relationship, like so:
class ProfileCourse(models.Model):
profile = models.ForeignKey(Profile)
course = models.ForeignKey(Course)
so then you can enroll a profile in a course with:
def course_signup(request):
profile = [snip....]
course = [snip...]
ProfileCourse(profile=profile, course=course).save()
One of the real advantages of managing your own m2m relationships is that you can add additional information to the relationship. In this case, you might add "final_grade".
One more thing...m2m relationships are often simply named after the two sides of the relationship (e.g. ProfileCourse), unless there is another good word (e.g. "Enrollment") that exists to describe the relationship.
Upvotes: 1