専門家ではない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つ作成しようとしています。これは、さまざまなオブジェクトを取得するときにさまざまなニーズに適応しますが、一般的な場合のデフォルトの動作も維持します。それとも、特別な場合のためにもっと多くのサブクラスを持っている方が良いですか?
アドバイスありがとうございます!