简体   繁体   English

Django通用UpdateView:获取要更新的对象

[英]Django generic UpdateView: Getting the object to be updated

I'm actually using the django.views.generic.edit.UpdateView to update a models specific fields. 我实际上是在使用django.views.generic.edit.UpdateView更新模型的特定字段。 Since I'm not passing the primary key or slug of the object to be updated, I'm simply overriding the get_object method: 由于我没有传递要更新的对象的主键或子get_object ,因此我只是覆盖了get_object方法:

def get_object(self, queryset=None):
    return Model.objects.get(user__id=self.request.user.id)

If there is no object found at get_object I'm receiving a 'Query does not match[...]' error, which is totally fine. 如果在get_object找不到任何对象,我将收到“查询不匹配[...]”错误,这是完全可以的。 But in case of an exception I'd like to redirect the user instead of showing the exception output. 但是在发生异常的情况下,我想重定向用户,而不是显示异常输出。 Unfortunately the get_object method forbids redirects as django expects it to return an object. 不幸的是,由于django希望它返回一个对象,因此get_object方法禁止重定向。

Is there any elegant way to check if the requested object exists and if not to redirect the user? 有什么优雅的方法可以检查所请求的对象是否存在以及是否不重定向用户? I'd also like to avoid overriding the dispatch method to perform the check for object existence there. 我还想避免重写dispatch方法以执行对对象是否存在的检查。 This would lead to an further unnecessary database query. 这将导致进一步不必要的数据库查询。 So I'd had three queries for a simple update view. 因此,对于一个简单的更新视图,我要进行三个查询。

Any advice would be really great :) 任何建议都将是非常好的:)

You could do the get in your get_object method, allow a DoesNotExist error to propagate (don't catch it), and override the dispatch method and catch the DoesNotExist exception there. 您可以在get_object方法中进行get ,允许传播DidNotExist错误(不捕获该错误),并覆盖分派方法并在其中捕获DidNotExist异常。 From dispatch, you can return a redirect. 从分派中,您可以返回重定向。

Something like: 就像是:

def dispatch(...):
    try:
         return super(...)  # call superclass dispatch
    except Model.DoesNotExist:
         return ... your redirection ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM