首页 > 解决方案 > 如何在 Djnago 中从多对多关系表中获取数据?

问题描述

我有多对多关系表。一个用户可以参加多门课程,这就是我想要做的。
我的模型是

class CourseModel(models.Model):
    course_name = models.CharField(max_length=255,blank=False)
    
    
class UserModel(models.Model):
    username = models.CharField(max_length=255)
    usercourses=models.ManyToManyField(CourseModel) #this code is creating saperate table in my database

我新创建的表的数据如下所示:

id : 1
usermodel_id : 7   # (any user_id can come here)
coursemodel_id : 10  #(any course id can come here)

id : 2
usermodel_id : 7
coursemodel_id : 11

正如我们在上面的数据中看到的,用户(7)参加了多门课程,例如 10,11。我想获取数据上方用户(7)表单的所有课程。如何做到这一点?

标签: djangodjango-modelsdjango-rest-frameworkdjango-formsdjango-views

解决方案


查看文档多对多关系

user = User.objects.get(pk=7)
user.usercourses.all() # gives all user (id=7) courses.

推荐阅读