In my models.py I have a model 'courses'. A course can have one name and one description but multiple links and instructors. I tried to stablish this using foreign key relationship. Now, lets say I want access the name of a particular course, I can do so by c.name where c would be an object obtained by using a filter query. But how would I access lets say the second instructor of that course? Also how would I add a new instructor to that course?
class courses(models.Model):
name=models.CharField(max_length=200)
description=models.TextField()
class links(models.Model):
link=models.CharField(max_length=200)
course=models.ForeignKey(courses,on_delete=models.CASCADE)
class instructors(models.Model):
inst=models.CharField(max_length=200)
course=models.ForeignKey(courses,on_delete=models.CASCADE)
Adding a new instructor requires a courses
object. So, you can do the following,
course = courses.objects.create(name="OS", description="course desc") instructor = instructors.objects.create(inst="name", course=course)
How are you defining the order of instructors? If it is the creation of instructors
object. then, you can access the second instructor of a course as the following.
all_instructors = instructors.objects.filter(course=course) if len(all_instructors) > 1: second_instructor = all_instructors[1]
NB You should rename your models to singular noun ie Course
, Link
, Instructor
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.