【问题标题】:Find model instance from table name in Django从Django中的表名中查找模型实例
【发布时间】:2018-07-07 19:18:36
【问题描述】:

我有下表。

class TempTable(models.Model):
    name = models.CharField(max_length=200)
    created_at = models.DateTimeField(auto_now_add=True)
    ...
    ...

    class Meta:
        db_table = 'temp_table'

现在假设我知道表名temp_table。目前我正在使用以下脚本从table name 获取model instance

from django.db.models import get_app, get_models

all_models = get_models()
for item in all_models:
    if item._meta.db_table == 'temp_table':
        return item

有没有更好的方法来实现这一点..??

【问题讨论】:

  • 我相信没有。 get_models() 返回可迭代的,这对内存很有用,而且这个函数用 @lru_cache 装饰,所以它根本不应该很重。
  • AFAIK,没有反向映射。 db_table 也不需要在您的项目中是唯一的,只需在一个应用程序中即可。因此,如果没有app_label,甚至不可能使用通用方法。

标签: python django model metaclass


【解决方案1】:

您可以像下面一样从模型名称访问模型实例,也可以检查表名称,但我认为您不需要这个;

        if hasattr("TempTable", "__class__"):
            mod = __import__("<your_app_name>.models", fromlist=["TempTable"])
            nclss = getattr(mod, "TempTable")
            # in here nclss is your model instance so you can use it
            # nclss.objects.all().order_by("id")
            return nclss
            # you can also check the table name but i think you did not need this
            if nclss._meta.db_table == "temp_table":
                return nclss

希望对你有用

【讨论】:

    猜你喜欢
    • 2011-08-06
    • 2022-01-12
    • 2014-06-27
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多