django - 如何在 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)表单的所有课程。如何做到这一点?
解决方案
查看文档多对多关系
user = User.objects.get(pk=7)
user.usercourses.all() # gives all user (id=7) courses.
推荐阅读
- r - 如何访问 ggplot2 扩展中的图例组 ID
- python - 入住日期和退房日期
- python - 在两个 pandas 列之间交换值
- listview - 当 Xamarin 表单中的可观察集合更新时,视图未更新
- java - 与自定义 ListView 中特定项目的视图交互
- r - '[.dt_df'(Final, i, index) 中的错误:找不到对象
- javascript - 在 WASM-Bindgen Rust 中使用鼠标输入事件上的闭包创建回调时闭包调用错误
- java - 使用 java 将声音上传到 myinstants.com
- maven - 我怎样才能让 jenkins/Jfrog 从我自己的工件和另一个远程工件中提取?
- python - 对服务模型使用 set MLFLOW_TRACKING_URI='http://0.0.0.0:5000' 时出错