【问题标题】:Automatically set the table name for a Django Model to the name of its class自动将 Django 模型的表名设置为其类的名称
【发布时间】:2018-12-26 20:03:53
【问题描述】:

目前,我的大部分模型都是这样的:

class A(models.Model):
    # model attributes
    class Meta:
        db_table = 'A'

class B(models.Model):
    # model attributes
    class Meta:
        db_table = 'B'

有没有办法自动做到这一点?我尝试在定义类后添加元类,但由于 Django 如何处理模型的元类,这不起作用。我只是坚持手动定义 Meta 类吗?

【问题讨论】:

  • 自动化什么?将数据库表命名为与类名完全一样?
  • @willem 假设 A 和 B 在名为“myapp”的应用程序中定义。然后默认表名将是“myapp_a” - 我希望它以某种方式默认为“A”
  • 我认为这回答了你的问题:stackoverflow.com/questions/27175106/…

标签: django python-3.x django-models


【解决方案1】:

不知道你为什么要这样做,但你可以这样做:

for model in models:
    model._meta.db_table = model.__class__.__name__

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多