Created
June 3, 2021 13:32
-
-
Save theArjun/69960abebb033d2c382592426f7916d5 to your computer and use it in GitHub Desktop.
Views for Product Variant
This file contains hidden or 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 ProductVariantViewset(DestroyMixin, ModelViewSet): | |
| ''' REST Endpoint for ProductVariant. ''' | |
| queryset = ProductVariant.objects.all() | |
| serializer_class = ProductVariantSerializer | |
| def create(self, request, *args, **kwargs): | |
| serializer = self.get_serializer(data=request.data) | |
| serializer.is_valid(raise_exception=True) | |
| variant = serializer.save() | |
| # Populate EAV fields | |
| extras = variant.extras | |
| if extras and len(extras.items()) > 0: | |
| attr_slugs = variant.eav.get_all_attribute_slugs() | |
| extra_values = { | |
| k: v | |
| for k, v in extras.items() | |
| if k[:3] == 'pv_' and k in attr_slugs | |
| } | |
| variant.extras = {} | |
| for key, value in extra_values.items(): | |
| setattr(variant.eav, key, value) | |
| variant.extras[key] = value | |
| variant.save() | |
| headers = self.get_success_headers(serializer.data) | |
| return Response(serializer.data, | |
| status=status.HTTP_201_CREATED, | |
| headers=headers) | |
| def update(self, request, *args, **kwargs): | |
| partial = kwargs.pop('partial', False) | |
| instance = self.get_object() | |
| serializer = self.get_serializer( | |
| instance, | |
| data=request.data, | |
| partial=partial, | |
| ) | |
| serializer.is_valid(raise_exception=True) | |
| variant = serializer.save() | |
| # Populate EAV fields | |
| extras: dict = variant.extras | |
| # Check if extra field is being populated. | |
| keys_len: int = len(extras.keys()) | |
| if keys_len == 0: | |
| pass | |
| else: | |
| # First remove the EAV values, so new can be populated. | |
| ProductVariantValue.objects.filter(entity_id=variant.id).delete() | |
| attr_slugs = variant.eav.get_all_attribute_slugs() | |
| extra_values = { | |
| k: v | |
| for k, v in extras.items() | |
| if k[:3] == 'pv_' and k in attr_slugs | |
| } | |
| variant.extras = {} | |
| for key, value in extra_values.items(): | |
| variant.extras[key] = value | |
| setattr(variant.eav, key, value) | |
| variant.save() | |
| if getattr(instance, '_prefetched_objects_cache', None): | |
| # If 'prefetch_related' has been applied to a queryset, we need to | |
| # forcibly invalidate the prefetch cache on the instance. | |
| instance._prefetched_objects_cache = {} | |
| return Response(serializer.data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment