Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
django我可以将模型的类型存储在变量中以用于方法调用吗?_Django - Fatal编程技术网

django我可以将模型的类型存储在变量中以用于方法调用吗?

django我可以将模型的类型存储在变量中以用于方法调用吗?,django,Django,我不确定python用什么术语来表示对象——请原谅我缺乏python专有技术 实际上,我如何才能做到这一点: strToObject = {'story':Story,'post':Post} def post(self,request): type = request.POST['theTypeInTheForm'] id = request.POST['idInTheForm'] get_object_or_404(strToObject.get(type,None

我不确定python用什么术语来表示对象——请原谅我缺乏python专有技术

实际上,我如何才能做到这一点:

strToObject = {'story':Story,'post':Post}

def post(self,request):
    type = request.POST['theTypeInTheForm']
    id = request.POST['idInTheForm']
    get_object_or_404(strToObject.get(type,None),id)
这样做的目的是从表单字段中获取一个值,计算出我们所说的类型,然后从db中从id中提取正确的类型


不过我不太知道怎么做。(该表单实际上是用于评级按钮的,因此我没有一个完整的表单!)

您可能想要使用它,它是一个包含应用程序中定义的所有不同模型的模型

您可能想要使用,它是一个包含应用程序中定义的所有不同模型的模型

首先,从
strToObject
获取模型时需要更加小心。目前,如果
type
不是“story”或“post”中的一个,那么
get\u object\u或_404
将作为模型输入
None
,您的代码将爆炸。改为这样做:

model = strToObject.get(type) # `None` is the "default" default
if model is not None:
    get_object_or_404(model, id=id)
其次,正如我在上面的代码中所指出的,您不能将
id
按原样传递给
get\u object\u或\u 404
,您需要指定应该在模型上查找值的字段,因此
id=id

第三,您应该在
请求中使用
get
。POST
获取
类型和
id
。现在,如果它们由于任何原因不在表单中,您的代码将被
索引器炸毁

type = request.POST.get('theTypeInTheForm')
id = request.POST.get('idInTheForm')
然后,在继续之前,应检查值是否为非
None

if type is not None and id is not None:
    # the rest of your code

首先,从
strToObject
获取模型时需要更加小心。目前,如果
type
不是“story”或“post”中的一个,那么
get\u object\u或_404
将作为模型输入
None
,您的代码将爆炸。改为这样做:

model = strToObject.get(type) # `None` is the "default" default
if model is not None:
    get_object_or_404(model, id=id)
其次,正如我在上面的代码中所指出的,您不能将
id
按原样传递给
get\u object\u或\u 404
,您需要指定应该在模型上查找值的字段,因此
id=id

第三,您应该在
请求中使用
get
。POST
获取
类型和
id
。现在,如果它们由于任何原因不在表单中,您的代码将被
索引器炸毁

type = request.POST.get('theTypeInTheForm')
id = request.POST.get('idInTheForm')
然后,在继续之前,应检查值是否为非
None

if type is not None and id is not None:
    # the rest of your code

嘿谢谢你的代码审查——我是认真的。这些都是你提出的好观点。我必须同意丹尼尔的回答——因为它回答了我提出的问题,但我非常感谢你的投入!嘿谢谢你的代码审查——我是认真的。这些都是你提出的好观点。我必须同意丹尼尔的回答——因为它回答了我提出的问题,但我非常感谢你的投入!啊。这是django设置的一个非常方便的系统。啊。这是django建立的一个非常方便的系统。