在Django中按变量模型名称访问模型 [英] Accessing models by variable model name in django

查看:72
本文介绍了在Django中按变量模型名称访问模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个相同的模型,比如说django中的X和Y:

I have two identical models, let's say X and Y in django like this:

class X(models.Model):
    con = models.CharField(max_length=100)
    a = models.ForeignField("FOO")

class Y(models.Model):
    con = models.CharField(max_length=100)
    b = models.ForeignField("BAR")

要访问这些模型的对象,我必须使用以下代码:

To access an object of these models, I have to use the following code:

models.X.objects.get(
    con = "something",
    a = xy
)

models.Y.objects.get(
    con = "something",
    b = yx
)

是否可以将模型名称设置为变量,例如 model_name = X ,然后使用此代码访问对象:

Is there a way to set the model name as variable such as model_name = X and then use this code to access the objects:

models.model_name.objects.get(**my_dict)

其中

my_dict = {"con":"something", "a":xy}

推荐答案

您可以执行以下操作:

getattr(models, model_name).objects.get(**my_dict)

它允许您通过字符串或变量访问模型的属性.

It allows you to access the attributes of models via strings or variables.

这篇关于在Django中按变量模型名称访问模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆