Skip to content

Instantly share code, notes, and snippets.

@gjbagrowski
Created January 30, 2017 17:56
Show Gist options
  • Save gjbagrowski/b0541d726dce67cab32c48cc3bc34ead to your computer and use it in GitHub Desktop.
Save gjbagrowski/b0541d726dce67cab32c48cc3bc34ead to your computer and use it in GitHub Desktop.
Mixin and inheritance example
class OrderStatus(object):
NEW = 'new'
PAID = 'paid'
DELIVERED = 'delivered'
CANCELLED = 'cancelled'
COMPLETED_STATES = (
DELIVERED,
CANCELLED,
)
class ReadOnlyViewSet(
mixins.RetrieveModelMixin,
mixins.ListModelMixin,
viewsets.GenericViewSet):
"""Common base view for readonly views, similar is provided by DRF.""""
pass
class PermissionsMixin(object):
""""
This mixin assumes that model has a company attribute that should
match the user.
"""
def get_queryset(self):
queryset = (
super(PermissionsMixin, self)
.get_queryset())
if self.request.user.is_superuser():
# admin
# extra query, aggregation?
pass
else:
# regular user
queryset = queryset.filter(company=self.request.user.company)
return queryset
class OrderView(PermissionsMixin, ReadOnlyViewSet):
""""Common view for order readonly views."""
queryset = Order.objects.all()
class CompletedOrderView(OrderView):
"""This filter does not rely on request."""
queryset = Order.objects.filter(
order_status__in=OrderStatus.COMPLETED_STATES
)
class RecentOrdersView(OrderView):
"""This filter does rely on time of request."""
def get_queryset(self):
return (
super(RecentOrderView, self)
.get_queryset()
.filter(created__gt=now() - datetime.timedelta(hours=2))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment