8

専門家ではないPythonプログラマーである私は、DjangoのSingleObjectMixinクラスのget_objectメソッドを拡張する方法についてのフィードバックを探しています。

ほとんどの詳細ビューでは、pkまたはslugfieldを使用したルックアップで問題ありませんが、場合によっては、「username」などの他の(一意の)フィールドに基づいてオブジェクトを取得する必要があります。DjangoのDetailViewをサブクラス化し、get_objectメソッドを次のように変更しました。

# extend the method of getting single objects, depending on model
def get_object(self, queryset=None):

    if self.model != mySpecialModel:
        # Call the superclass and do business as usual 
        obj = super(ObjectDetail, self).get_object()
        return obj

    else:
        # add specific field lookups for single objects, i.e. mySpecialModel
        if queryset is None:
            queryset = self.get_queryset()

        username = self.kwargs.get('username', None)
        if username is not None:
            queryset = queryset.filter(user__username=username)
        # If no username defined, it's an error.
        else:
            raise AttributeError(u"This generic detail view %s must be called with "
                                 u"an username for the researcher."
                                 % self.__class__.__name__)

        try:
            obj = queryset.get()
        except ObjectDoesNotExist:
            raise Http404(_(u"No %(verbose_name)s found matching the query") %
                          {'verbose_name': queryset.model._meta.verbose_name})
        return obj

これは良い習慣ですか?Detailviewのサブクラスを1つ作成しようとしています。これは、さまざまなオブジェクトを取得するときにさまざまなニーズに適応しますが、一般的な場合のデフォルトの動作も維持します。それとも、特別な場合のためにもっと多くのサブクラスを持っている方が良いですか?

アドバイスありがとうございます!

4

2 に答える 2

10

slug_fieldクラスの変数DetailViewを、ルックアップに使用するモデルフィールドに設定できます。URLパターンでは、常に名前slugを付ける必要がありますが、必要なすべてのモデルフィールドにマップできます。

さらに、デフォルトでのみ返されるDetailView's -methodをオーバーライドすることもできます。get_slug_fieldself.slug_field

于 2011-07-22T11:41:14.360 に答える
0

継承を使用できますか?

class FooDetailView(DetailView):
    doBasicConfiguration

class BarDetailView(FooDetailView):
    def get_object(self, queryset=None):
        doEverythingElse
于 2011-12-22T15:13:20.807 に答える