[英]Find model instance from table name in Django
我有下表。
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
我希望這個對你有用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.