def to_representation(self, obj): return { 'id': obj.id, 'name': obj.name, 'source': obj.source, 'category': obj.category, 'status': obj.status, 'tags': obj.tags, 'imports': obj.imports, 'scopes': obj.scopes, 'metadata': obj.metadata, 'dependencies': self.get_dependencies(obj), 'formatted_rule': self.get_formatted_rule(obj), 'submitter': PublicUserSerializer(obj.submitter).data, 'comments': YaraRuleCommentSerializer(obj.yararulecomment_set.all(), many=True).data, 'created': obj.created, 'modified': obj.modified }
class YaraRuleCommentSerializer(serializers.Serializer): content = serializers.CharField() poster = PublicUserSerializer(read_only=True) id = serializers.IntegerField(read_only=True) created = serializers.DateTimeField(read_only=True) modified = serializers.DateTimeField(read_only=True) def retrieve_request_user(self): request = self.context.get("request") request_user = request.user return request_user def create(self, validated_data): # Retrieve rule object identifier from calling view kwargs rule_identifier = self.context['view'].kwargs['rule_pk'] try: rule_object = YaraRule.objects.get(id=rule_identifier) except: raise serializers.ValidationError("Non-existent rule") else: validated_data['rule'] = rule_object # Generate timestamps validated_data['created'] = datetime.datetime.now() validated_data['modified'] = datetime.datetime.now() # Retrieve submitting user validated_data['poster'] = self.retrieve_request_user() return YaraRuleComment.objects.create(**validated_data) def update(self, instance, validated_data): instance.modified = datetime.datetime.now() instance.content = validated_data.get('content', instance.content) instance.save() return instance