2016-03-30 4 views
0

のは、私は次のモデルがあるとしましょう:ジャンゴジェネリックUpdateViewとマルチテーブル継承

class Post(model): 
    ... 

class BlogPost(Post): 
    ... 

class OtherPost(Post): 
    ... 

は、投稿を編集するために、私のURLスキーマを想定言い換えれば

/site/post/\d+/edit 

、のようなものですが、私は「ドンOtherPostsBlogPostの編集に別々のURLパスがあります。

UpdateViewを使用する場合、モデルを設定する必要がありますが、実際のモデルはPostのサブクラスです。

class Update(generics.UpdateView): 
    model = Post 

これを処理するDjangoey/DRYの方法は何ですか?私はUpdate.model未定義のままにして、右のサブモデルでクエリを返す必要があるだろうget_querysetをオーバーライドすることができますようにUpdateViewコードを見ている瞬間

は、それが見えます。また、正しい書式を返すには、 get_formを上書きする必要があります。

私はそれがうまくいくと私の解決策を投稿しますが、おそらくより良い(DRYer)統合を探しています。

答えて

0

次の方法が動作しているようですが、これはかなり小さいようです。

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のような多型のミックスインを使用している場合:

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()