简体   繁体   English

查询具有外键关系的 Django 模型

[英]querying a django model with foreign key relationship

In my models.py I have a model 'courses'.在我的 models.py 中,我有一个模型“课程”。 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.现在,假设我想访问特定课程的名称,我可以通过 c.name 这样做,其中 c 将是使用过滤器查询获得的对象。 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)
  1. Adding a new instructor requires a courses object.添加新教师需要一个courses对象。 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.如果是创建instructors对象。 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注意您应该将模型重命名为单数名词,即CourseLinkInstructor

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM