Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ProductImageSerializer(serializers.ModelSerializer):
- 1 violated = serializers.SerializerMethodField()
- 2
- 3 def get_violated(self, obj):
- 4 return obj.found_copyright_violations.exists() # if there are violations
- 5
- 6 class Meta:
- 7 model = ProductImage
- 8 fields = ('product', 'image_id', 'url', 'selected', 'violated')
- 9 # otherwise, there will be validation errors
- 10 extra_kwargs = {"image_id": {"validators": []}}
- 11
- 12
- 13 class ProductSerializer(serializers.ModelSerializer):
- 14 images = ProductImageSerializer(many=True)
- 15
- 16 class Meta:
- 17 model = Product
- 18 fields = ('product_id', 'title', 'images', 'active')
- 19
- 20 def update(self, instance, validated_data):
- 21 # Updating images selected field
- 22 for image_data in validated_data.get("images"):
- >> 23 image_instance = ProductImage.objects.get(
- 24 pk=image_data.get("image_id"),
- 25 )
- 26
- 27 image_instance.selected = image_data.get("selected")
- 28 image_instance.save()
- 29
- 30 selected_images = instance.images.filter(selected=True)
- 31
- 32 # If there are selected images, set to either true or false.
- 33 if selected_images:
- 34 instance.active = validated_data.get('active', instance.active)
- 35 # Otherwise false
- 36 else:
- 37 instance.active = False
- 38
- 39 instance.save()
- 40
- 41 return instance
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement