Django 管理多对多表名
我可以为多对多表指定我想要的名称吗?
Can I specify the name I want for the many to many table?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我可以为多对多表指定我想要的名称吗?
Can I specify the name I want for the many to many table?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(3)
是的。有关所有令人兴奋的详细信息,请参阅表名称 。
更新:好的,那么也许是
lated_name
选项就是您要寻找的。有一些警告 此处介绍。Updatex2:好吧,凯尔文因为回答了自己的问题而获得了一颗星星!自从我仔细阅读 Django 元模型选项以来,已经有一段时间了,但回想起来,这才是我们应该开始的地方。
顺便说一句,仅喝半杯咖啡就浏览 django/db/ 代码绝对是一个挑战。
Yes. See Table Names for all of the exciting details.
Update: OK, then perhaps the
related_name
option is what you are looking for. There are some caveats covered here.Updatex2: OK, Kelvin gets a star for answering his own question! It's been an age since I perused the Django Meta Model Options, but, in retrospect, that's where we should have started.
BTW, wandering through the
django/db/
code on only half a cup of coffee is definitely a challenge.您可以在声明
ManyToManyField
属性时使用db_table
选项定义表名称。请参见下面的示例:lated_name
是issue
可以通过该类看到该类的字段,这意味着您将通过my_issue.revisions()
来访问它>。数据库中使用的表名为issue_revision
。You define the table name using the
db_table
option when declaring theManyToManyField
attribute. See example below:related_name
is the field by which this class will be seen byissue
, meaning, you will access it asmy_issue.revisions()
. And the table being used in the DB is namedissue_revision
.msb的答案效果很好,
但是,如果(像我一样)您需要将其设置为相同的名称(因为已知命名问题 mysql-django 后端),您需要在迁移中注册它。
新的问题是,当你运行自动创建的新迁移时,Django将尝试创建一个同名的新表,这将抛出“数据库已存在”错误。
因此,您需要返回到创建
ManyToManyField
的原始迁移并添加您在其中包含的内容。例如:
app/models.py
:app/migrations/0003_.py
:如果您编辑创建字段的原始迁移,则无需再<代码>makemigrations和
migrate
。msb's answer works great,
however if (like me) you needed to set it to the same name (because of known naming issues mysql-django backend), you would need to register it in a migration.
The new problem is that Django will try to create a new table of the same name when you run the automatically created new migrations, which will throw a "database already exists" error.
You would thus need to go back to the original migration where that
ManyToManyField
was created and add what you included there.For example:
app/models.py
:app/migrations/0003_.py
:If you edit the original migration where the field was created, there is no further need to
makemigrations
andmigrate
.