Django Generic UpdateView和多表继承



假设我有以下模型:

class Post(model):
    ...
class BlogPost(Post):
    ...
class OtherPost(Post):
    ...

假设我编辑帖子的url模式类似于

/site/post/d+/edit

换句话说,我没有单独的url路径来编辑OtherPostsBlogPost

当使用UpdateView时,我需要设置模型——但当然,实际的模型是Post的一个子类。

class Update(generics.UpdateView):
    model = Post

Djangey/DRY处理这个问题的方法是什么?

目前,查看UpdateView代码,我似乎可以不定义Update.model,并覆盖get_queryset,这需要返回一个具有正确子模型的查询。我还需要覆盖get_form以返回正确的表单。

当我的解决方案工作时,我会发布它,但我正在寻找可能更好的(DRYer)集成。

看起来下面的方法正在工作,这看起来相当简单。

class Update(generic.edit.UpdateView):
    model = Post
    def get_form_class(self):                                                   
      try:                                                                    
          if self.object.blogpost:                                    
              return BlogPostForm
      except Post.DoesNotExist:                                          
          pass                                                                
      try:                                                                    
          if self.object.otherpost:                                     
              return OtherPostForm                                
      except Post.DoesNotExist:                                          
          pass                                                                
      def get_object(self, queryset=None):                                        
          object = super(Update, self).get_object(queryset)                       
          try:                                                                    
              return object.blogpost
          except Post.DoesNotExist:                                          
              pass                          
          try:                                                                    
              return object.otherpost
          except Post.DoesNotExist:                                          
              pass                                  

或者,如果使用像InheritanceManager这样的多态mixin,那么如下所示:

class Update(generic.edit.UpdateView):
    model = Post
    form_class = {
        BlogPost: BlogPostForm,
        OtherPost: OtherPostForm,
    }
    def get_form_class(self):                                                   
       return self.form_class[self.object.__class__]
   def get_queryset(self):                                                     
      return self.model.objects.select_subclasses() 

最新更新