设计“视频”和“视频列表”表,如 Youtube 的表,使用 Django
我正在使用 Django 制作一个带有“视频”和“视频列表”表的应用程序,例如 YouTube 的表。
现在,我正在制作一个“视频”和“课程(这是一个视频列表)”表。 我想将一个视频添加到一些不同的列表中,并按列表和视频进行搜索, 所以让 Course 表有 ManyToMany 字段链接到 Video 表。
但通过这种方式,我在列表中的视频顺序方面遇到了一些困难。 为了按照我注册的顺序显示视频并在之后随时修复它们,ManyToMany 字段在注册时必须有类似“id”的内容,对吧?
我是Python和Django的初学者,所以可能有一些典型的方法...... 有什么好的办法来处理这个问题吗?
I'm making an app with video" and "video list" tables, like YouTube ones, using Django.
Now, I'm making a "Video" and "Course(this is a video list)" table.
I want to add one video to some different lists and search by both list and video,
so let Course table have ManyToMany field link to Video table.
But in this way, I have some difficulty in videos' order in a list.
To display videos in the order I registered and to fix them anytime after, ManyToMany field must have something like "id" when it is registered, right?
I'm a beginner of both Python and Django, so there may be some typical way...
Any good ways to deal with this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过创建自己的中间模型(而不是使用 Django 创建的隐式模型)来完成此操作:
上面的重要部分是
ManyToManyField
上的through
属性。这告诉 Django 使用您定义的 CourseVideo 模型而不是它自己的隐式版本。但是,执行此操作时会遇到一些问题。您不能再使用诸如
some_course.videos.add(video)
之类的内容,因为现在需要其他信息来创建该关系。相反,您需要显式创建关系:有关更多详细信息,请参阅文档: https://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany
You do this by creating your own intermediary model (instead of using the implicit one created by Django):
The important part above is the
through
attribute on theManyToManyField
. This tells Django to use theCourseVideo
model you defined instead of its own implicit version.However, there's a few gotchas when you do this. You can no longer use things like
some_course.videos.add(video)
, because additional information is needed now to create that relationship. Instead, you need to create the relationship explicitly:See the documentation for more details: https://docs.djangoproject.com/en/dev/topics/db/models/#intermediary-manytomany