Skip to main content
 首页 » 编程设计

python之从 Django 中的表名中查找模型实例

2025年05月04日29lonelyxmas

我有下表。

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 

有没有更好的方法来实现这个……??

请您参考如下方法:

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

        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 

希望对你有用