0

Django では、動物が好きなアプリケーションからの抜粋を以下に示します。

以下の動物/models.py :

from django.db import models
from django.contrib.contenttypes.models import ContentType

class Animal(models.Model):
  content_type = models.ForeignKey(ContentType,editable=False,null=True)
  name = models.CharField()

class Dog(Animal):
  is_lucky = models.BooleanField()

class Cat(Animal):
  lives_left = models.IntegerField()

そしてanimal/urls.py :

from django.conf.urls.default import *

from animals.models import Animal, Dog, Cat

dict = { 'model' : Animal }

urlpatterns = (
  url(r'^edit/(?P<object_id>\d+)$', 'create_update.update_object', dict),
)

一般的なビューを使用して、同じフォームを使用して犬や猫を編集するにはどうすればよいですか?

すなわち、 animals/animal_form.htmlに渡されるフォームオブジェクトはAnimal になるため、派生クラス Dog および Cat の詳細は含まれません。Django に子クラスのフォームをanimal/animals_form.htmlに自動的に渡すにはどうすればよいですか?

ちなみに、私はContentType の管理にDjangosnippets #1031を使用しているため、Animalには派生クラスを返すas_leaf_classという名前のメソッドがあります。

明らかに、派生クラスごとにフォームを作成することもできますが、それはかなりの不要な重複です (テンプレートはすべてジェネリックになるため、基本的には {{ form.as_p }})。

ちなみに、Animal はおそらく同じ問題を抱えたいくつかの無関係な基本クラスの 1 つであると想定するのが最善です。そのため、理想的な解決策はジェネリックです。

助けてくれてありがとう。

4

2 に答える 2

1

よし、これが私がやったことであり、それは機能し、賢明な設計のようです (ただし、修正する必要があります!)。

コア ライブラリ (mysite.core.views.create_update など) で、デコレータを作成しました。

from django.contrib.contenttypes.models import ContentType
from django.views.generic import create_update

def update_object_as_child(parent_model_class):
   """
   Given a base models.Model class, decorate a function to return  
   create_update.update_object, on the child class.

   e.g.
   @update_object(Animal)
   def update_object(request, object_id):
      pass

  kwargs should have an object_id defined.
  """

  def decorator(function):
      def wrapper(request, **kwargs):
          # may raise KeyError
          id = kwargs['object_id']

          parent_obj = parent_model_class.objects.get( pk=id )

          # following http://www.djangosnippets.org/snippets/1031/
          child_class = parent_obj.content_type.model_class()

          kwargs['model'] = child_class

          # rely on the generic code for testing/validation/404
          return create_update.update_object(request, **kwargs)
      return wrapper

  return decorator

そして、animals/views.py には次のものがあります。

from mysite.core.views.create_update import update_object_as_child

@update_object_as_child(Animal)
def edit_animal(request, object_id):
  pass

そして、animals/urls.py には次のものがあります。

urlpatterns += patterns('animals.views',
  url(r'^edit/(?P<object_id>\d+)$', 'edit_animal', name="edit_animal"),
)

これで、基本クラスごとに固有の編集機能だけが必要になりました。これは、デコレータで簡単に作成できます。

誰かが役に立てば幸いです。フィードバックをいただければ幸いです。

于 2008-10-18T19:40:12.103 に答える
0

AFAICT、猫と犬は異なるDBテーブルにあり、動物テーブルがない可能性があります。ただし、すべてに1つのURLパターンを使用しています。どこかでそれぞれから選択する必要があります。

猫と犬には別のURLパターンを使用しますが、どちらも'create_update.update_object';を呼び出します。ただし、それぞれに異なるものdictを使用します。1つはと'model':Dog、もう1つは'model':Cat

または、各レコードが猫または犬になることができる単一のテーブルが必要ですか?そのために継承されたモデルを使用できるとは思いません。

于 2008-10-17T18:51:06.433 に答える