如何让我的视图更好地拯救 Django
大家对这篇文章感到抱歉,但我需要有关我的应用程序的帮助,我需要优化我的视图。我有 5 个模型,我该怎么做?
def save(request):
# get the request.POST in content
if request.POST:
content = request.POST
dicionario = {}
# create a dict to get the values in content
for key,value in content.items():
# get my fk Course.objects
if key == 'curso' :
busca_curso = Curso.objects.get(id=value)
dicionario.update({key:busca_curso})
else:
dicionario.update({key:value})
#create the new teacher
Professor.objects.create(**dicionario)
我的问题是?
1 - 我如何以通用方式执行此功能?我可以在 %s 中传递一个变量来创建和 得到?喜欢这样吗?
foo = "Teacher" , bar = "Course"
def save(request, bar, foo):
if request post:
...
if key == 'course' :
get_course = (%s.objects.get=id=value) %bar
...
(%s.objects.create(**dict)) %foo ???
在我看来,我尝试这样做,但不起作用=/,有人可以帮助我完成这项工作吗?谢谢
Hy guys sorry for this post but i need help with my application, i need optimize my view. I have 5 models, how i can do this?
def save(request):
# get the request.POST in content
if request.POST:
content = request.POST
dicionario = {}
# create a dict to get the values in content
for key,value in content.items():
# get my fk Course.objects
if key == 'curso' :
busca_curso = Curso.objects.get(id=value)
dicionario.update({key:busca_curso})
else:
dicionario.update({key:value})
#create the new teacher
Professor.objects.create(**dicionario)
my questions are?
1 - How i can do this function in a generic way? Can I pass a variable in a %s to create and
get? like this way ?
foo = "Teacher" , bar = "Course"
def save(request, bar, foo):
if request post:
...
if key == 'course' :
get_course = (%s.objects.get=id=value) %bar
...
(%s.objects.create(**dict)) %foo ???
i tried do this in my view but don't work =/, can somebody help me to make this work ? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用 ModelForms,而不是手动执行这一切。这样您就可以简单地创建一个表单,该表单将在调用
save()
时自动创建您的对象。例子:
Instead of doing this all manually you should use ModelForms. That way you can simply create a form that will automatically create your object upon calling
save()
.Example:
由于您有多个表单,因此您实际上需要表单集: http:// /docs.djangoproject.com/en/dev/topics/forms/formsets/
文档出色地描述了如何将带有查询集的表单放入表单集中,以便一次编辑多个内容:)
Since you have more than one of these forms, you actually want formsets: http://docs.djangoproject.com/en/dev/topics/forms/formsets/
The docs do a fantastic job of describing how to throw a form with a queryset together into a formset to edit more than one thing at a time :)