我具有以下视图来创建(列出)与特定事件相关的注释。我试图找出一种更干净的方法来创建/获取实例,而不会像我一样覆盖get_queryset()
和get_object()
方法。
网址看起来像这样:
/events/v1/events/{id}/comments/
因此,我只有事件ID,每个用户都可以为此事件获取评论,或者用户可以为此事件创建评论。
class EventCommentsAPIView(generics.ListCreateAPIView):
serializer_class = CommentSerializer
pagination_class = BaseResultsSetPagination
filter_class = TimeStampedFilter
def __init__(self):
super().__init__()
self.content_type = self.get_contenttype()
def get_queryset(self):
return Comment.objects.filter(
content_type=self.content_type,
reply_on=None,
object_id=self.get_object().id).prefetch_related(
'replies')
def get_object(self):
queryset = Event.objects.filter(id=self.kwargs.get('pk'))
return get_object_or_404(queryset)
@staticmethod
def get_contenttype():
# TODO ADD Caching
return ContentType.objects.get(model='event')
def get_serializer_context(self):
"""
Extra context provided to the serializer class.
"""
return {'request': self.request,
'format': self.format_kwarg,
'view': self,
'content_type': self.content_type,
'pk': self.kwargs.get('pk')}
如果需要,这是我的序列化器:
class CommentSerializer(serializers.ModelSerializer, CreatorMixin):
replies = ShortCommentSerializer(many=True, read_only=True)
reply_on = serializers.PrimaryKeyRelatedField(
queryset=Comment.objects.all(),
write_only=True,
allow_null=True,
required=False
)
class Meta:
model = Comment
fields = ('id', 'text', 'object_id', 'creator', 'replies',
'reply_on', 'created')
extra_kwargs = {
'text': {'required': True},
'object_id': {'read_only': True}
}
def create(self, validated_data):
validated_data.update(
{
'content_type': self.context['content_type'],
'object_id': self.context['pk'],
'creator': self.context['request'].user
}
)
return Comment.objects.create(**validated_data)