本文整理汇总了Python中rest_framework.decorators.action方法的典型用法代码示例。如果您正苦于以下问题:Python decorators.action方法的具体用法?Python decorators.action怎么用?Python decorators.action使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类rest_framework.decorators
的用法示例。
在下文中一共展示了decorators.action方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_queryset
# 需要导入模块: from rest_framework import decorators [as 别名]
# 或者: from rest_framework.decorators import action [as 别名]
def get_queryset(self):
if self.action in ('partial_update', 'thread'):
return self.queryset
qs = self.queryset \
.with_conversation_access(self.request.user) \
.annotate_replies_count() \
.annotate_unread_replies_count_for(self.request.user)
if self.action == 'my_threads':
return qs.only_threads_with_user(self.request.user) \
.prefetch_related('participants', 'latest_message')
if self.action == 'list':
qs = qs.prefetch_related('reactions', 'participants')
if self.request.query_params.get('thread', None):
return qs.only_threads_and_replies()
return qs.exclude_replies()
示例2: get_serializer_class
# 需要导入模块: from rest_framework import decorators [as 别名]
# 或者: from rest_framework.decorators import action [as 别名]
def get_serializer_class(self):
"""
Users should receive the DetailedUserSerializer if they tries to get themselves or have the
EDIT permission.
"""
if self.action in ["retrieve", "update", "partial_update"]:
try:
instance = self.get_object()
except AssertionError:
return PublicUserWithGroupsSerializer
if (
self.request.user.has_perm(EDIT, instance)
or self.request.user == instance
):
return MeSerializer
return PublicUserWithGroupsSerializer
elif self.action == "create":
return RegistrationConfirmationSerializer
return super().get_serializer_class()
示例3: update
# 需要导入模块: from rest_framework import decorators [as 别名]
# 或者: from rest_framework.decorators import action [as 别名]
def update(self, request, *args, **kwargs):
partial = kwargs.pop("partial", False)
user = self.get_object()
serializer = self.get_serializer(user, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
is_abakus_member = serializer.validated_data.pop("is_abakus_member", None)
with transaction.atomic():
super().perform_update(serializer)
if is_abakus_member is None or is_abakus_member == user.is_abakus_member:
return Response(data=serializer.data, status=status.HTTP_200_OK)
if not user.is_verified_student():
raise ValidationError(
detail="You have to be a verified student to perform this action"
)
abakus_group = AbakusGroup.objects.get(name=constants.MEMBER_GROUP)
if is_abakus_member:
abakus_group.add_user(user)
else:
abakus_group.remove_user(user)
payload = serializer.data
payload["is_abakus_member"] = is_abakus_member
return Response(data=payload, status=status.HTTP_200_OK)
示例4: get_queryset
# 需要导入模块: from rest_framework import decorators [as 别名]
# 或者: from rest_framework.decorators import action [as 别名]
def get_queryset(self):
user = self.request.user
if self.action in ["list", "upcoming"]:
queryset = Event.objects.select_related("company").prefetch_related(
"pools", "pools__registrations", "tags"
)
elif self.action == "retrieve":
queryset = Event.objects.select_related(
"company", "responsible_group"
).prefetch_related("pools", "pools__permission_groups", "tags")
if user and user.is_authenticated:
reg_queryset = self.get_registrations(user)
queryset = queryset.prefetch_related(
"can_edit_users",
"can_edit_groups",
Prefetch("pools__registrations", queryset=reg_queryset),
Prefetch("registrations", queryset=reg_queryset),
)
else:
queryset = Event.objects.all()
return queryset
示例5: get_queryset
# 需要导入模块: from rest_framework import decorators [as 别名]
# 或者: from rest_framework.decorators import action [as 别名]
def get_queryset(self):
queryset = super().get_queryset()
if self.action in ["popular", "list"]:
# Usage count
related_fields = [
related.name for related in queryset.model._meta.related_objects
]
annotation = Count(related_fields[0])
for related in related_fields[1:]:
annotation += Count(related)
return queryset.annotate(usages=annotation)
if self.action == "retrieve":
# Usage count and relation counts
related_fields = [
related.name for related in queryset.model._meta.related_objects
]
annotation = Count(related_fields[0])
for related in related_fields[1:]:
annotation += Count(related)
annotations = {f"{field}_count": Count(field) for field in related_fields}
return queryset.annotate(usages=annotation, **annotations)
return queryset
示例6: get_annotations_queryset
# 需要导入模块: from rest_framework import decorators [as 别名]
# 或者: from rest_framework.decorators import action [as 别名]
def get_annotations_queryset(self, only_true_annotations=False):
"""
Get project annotations using SavedFilter logic to filter out FieldAnnotations*
"""
project = self.get_object()
request = HttpRequest()
request.user = self.request.user
request.GET = self.request.data
from apps.document.api.v1 import DocumentFieldAnnotationViewSet as api_view
view = api_view(request=request, kwargs={'project_pk': project.pk})
view.action = 'list'
qs = view.get_queryset(only_true_annotations=only_true_annotations)
return qs
示例7: assign_annotations
# 需要导入模块: from rest_framework import decorators [as 别名]
# 或者: from rest_framework.decorators import action [as 别名]
def assign_annotations(self, request, **kwargs):
"""
Bulk assign batch of annotations to a review team member\n
Params:
annotation_ids: list[int]
all: any value - update all annotations if any value
no_annotation_ids: list[int] - exclude those annotations from action (if "all" is set)
assignee_id: int
Returns:
int (number of reassigned annotations)
"""
self.get_object() # noqa: permissions check
assignee_id = request.data.get('assignee_id')
annotations = self.get_annotations_queryset()
# re-fetch annotations as initial values-qs doesn't allow update
ant_uids = [i['uid'] for i in annotations]
true_annotations = FieldAnnotation.objects.filter(uid__in=ant_uids)
true_annotations.update(assignee=assignee_id, assign_date=now())
false_annotations = FieldAnnotationFalseMatch.objects.filter(uid__in=ant_uids)
false_annotations.update(assignee=assignee_id, assign_date=now())
return Response({'success': annotations.count()})
示例8: to_representation
# 需要导入模块: from rest_framework import decorators [as 别名]
# 或者: from rest_framework.decorators import action [as 别名]
def to_representation(self, instance):
ret = super().to_representation(instance)
view = self.context['view']
if view.action == 'retrieve':
# get prev/next FieldValue id using the same sort order and filters from list view
qs = view.get_queryset()
qs = view.filter_queryset(qs)
ids = list(qs.filter(field=instance.field).values_list('pk', flat=True))
pos = ids.index(instance.pk)
prev_ids = ids[:pos]
next_ids = ids[pos + 1:]
ret['prev_id'] = prev_ids[-1] if prev_ids else None
ret['next_id'] = next_ids[0] if next_ids else None
ret['annotations'] = FieldAnnotation.objects.filter(field=instance.field, document=instance.document) \
.values('pk', 'location_start', 'location_end', 'location_text')
return ret
示例9: get_permissions
# 需要导入模块: from rest_framework import decorators [as 别名]
# 或者: from rest_framework.decorators import action [as 别名]
def get_permissions(self):
"""Instantiate and return the list of permissions that this view requires."""
if self.action == "metadata":
permission_classes = [permissions.IsVideoToken]
else:
permission_classes = [
permissions.IsVideoRelatedAdmin | permissions.IsVideoRelatedInstructor
]
return [permission() for permission in permission_classes]
示例10: get_permissions
# 需要导入模块: from rest_framework import decorators [as 别名]
# 或者: from rest_framework.decorators import action [as 别名]
def get_permissions(self):
"""Assign permission based on action."""
permissions = [IsAuthenticated, IsActiveCircleMember]
if self.action in ['update', 'partial_update', 'finish']:
permissions.append(IsRideOwner)
if self.action == 'join':
permissions.append(IsNotRideOwner)
return [p() for p in permissions]
示例11: get_serializer_class
# 需要导入模块: from rest_framework import decorators [as 别名]
# 或者: from rest_framework.decorators import action [as 别名]
def get_serializer_class(self):
"""Return serializer based on action."""
if self.action == 'create':
return CreateRideSerializer
if self.action == 'join':
return JoinRideSerializer
if self.action == 'finish':
return EndRideSerializer
if self.action == 'rate':
return CreateRideRatingSerializer
return RideModelSerializer
示例12: get_queryset
# 需要导入模块: from rest_framework import decorators [as 别名]
# 或者: from rest_framework.decorators import action [as 别名]
def get_queryset(self):
"""Return active circle's rides."""
if self.action not in ['finish', 'retrieve']:
offset = timezone.now() + timedelta(minutes=10)
return self.circle.ride_set.filter(
departure_date__gte=offset,
is_active=True,
available_seats__gte=1
)
return self.circle.ride_set.all()
示例13: get_permissions
# 需要导入模块: from rest_framework import decorators [as 别名]
# 或者: from rest_framework.decorators import action [as 别名]
def get_permissions(self):
"""Assign permissions based on action."""
permissions = [IsAuthenticated]
if self.action != 'create':
permissions.append(IsActiveCircleMember)
if self.action == 'invitations':
permissions.append(IsSelfMember)
return [p() for p in permissions]
示例14: get_permissions
# 需要导入模块: from rest_framework import decorators [as 别名]
# 或者: from rest_framework.decorators import action [as 别名]
def get_permissions(self):
"""Assign permissions based on action."""
if self.action in ['signup', 'login', 'verify']:
permissions = [AllowAny]
elif self.action in ['retrieve', 'update', 'partial_update', 'profile']:
permissions = [IsAuthenticated, IsAccountOwner]
else:
permissions = [IsAuthenticated]
return [p() for p in permissions]
示例15: get_serializer_class
# 需要导入模块: from rest_framework import decorators [as 别名]
# 或者: from rest_framework.decorators import action [as 别名]
def get_serializer_class(self):
if self.action in ['content', 'set_content']:
return RelatedFileSerializer
else:
return super(DataFileViewset, self).get_serializer_class()