Created
January 30, 2017 17:56
-
-
Save gjbagrowski/b0541d726dce67cab32c48cc3bc34ead to your computer and use it in GitHub Desktop.
Mixin and inheritance example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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