使用过滤器/ Django ORM 查找模型对象时如何使用字符串变量作为字段名?
How to use a string variable as a fieldname when looking up a model object using filter / the Django ORM?
这是我的代码:
PostModels = {
'dPost': DPost,
'sPost': SPost,
'rPost': RPostModel,
}
for postType, Post in PostModels.items():
try:
post = Post.objects.get(pk=pk)
except:
pass
else:
return RPostModel.objects.filter(postType=post)
当我做post = Post.objects.get(pk=pk)
时,Post
是for循环中的变量Post
。所以在第一个循环中,它搜索 DPost
中的对象,在下一个循环中它搜索 SPost
等。但是,当它到达 return 语句时,它给出一个错误说:
django.core.exceptions.FieldError:
Cannot resolve keyword 'postType' into field.
Choices are: createdAt, dPost, dPost_id, sPost, sPost_id, rPost, rPost_id
如何使 postType
等于 postType
变量的值?换句话说,在循环中,如何让我的 return 语句成为这些语句:
return RPostModel.objects.filter(dPost=post)
return RPostModel.objects.filter(sPost=post)
return RPostModel.objects.filter(rPost=post)
而不是这个:
return RPostModel.objects.filter(postType=post)
试试这个:
for postType, Post in PostModels.items():
try:
post = Post.objects.get(pk=pk)
except:
pass
else:
kwargs = {postType: post}
return RPostModel.objects.filter(**kwargs)
这是我的代码:
PostModels = {
'dPost': DPost,
'sPost': SPost,
'rPost': RPostModel,
}
for postType, Post in PostModels.items():
try:
post = Post.objects.get(pk=pk)
except:
pass
else:
return RPostModel.objects.filter(postType=post)
当我做post = Post.objects.get(pk=pk)
时,Post
是for循环中的变量Post
。所以在第一个循环中,它搜索 DPost
中的对象,在下一个循环中它搜索 SPost
等。但是,当它到达 return 语句时,它给出一个错误说:
django.core.exceptions.FieldError:
Cannot resolve keyword 'postType' into field.
Choices are: createdAt, dPost, dPost_id, sPost, sPost_id, rPost, rPost_id
如何使 postType
等于 postType
变量的值?换句话说,在循环中,如何让我的 return 语句成为这些语句:
return RPostModel.objects.filter(dPost=post)
return RPostModel.objects.filter(sPost=post)
return RPostModel.objects.filter(rPost=post)
而不是这个:
return RPostModel.objects.filter(postType=post)
试试这个:
for postType, Post in PostModels.items():
try:
post = Post.objects.get(pk=pk)
except:
pass
else:
kwargs = {postType: post}
return RPostModel.objects.filter(**kwargs)