Sunvir
Sunvir

Reputation: 57

querying a django model with foreign key relationship

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)

Upvotes: 0

Views: 30

Answers (1)

Hasan
Hasan

Reputation: 968

  1. 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)
    
  2. 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]
    

    N.B. You should rename your models to singular noun i.e. Course, Link, Instructor

Upvotes: 1

Related Questions