Esempio n. 1
0
class XFormSerializer(serializers.ModelSerializer):
    """
    Serializer for XForm Model
    """
    task_name = serializers.SerializerMethodField()
    metadata = serializers.SerializerMethodField()

    class Meta:  # pylint: disable=too-few-public-methods
        """
        Meta Options for XForm Serializer
        """
        model = XForm
        fields = [
            'id', 'ona_pk', 'ona_project_id', 'last_updated', 'title',
            'id_string', 'version', 'created', 'modified', 'deleted_at',
            'has_task', 'task_name', 'project', 'metadata'
        ]

    def get_metadata(self, obj):  # pylint: disable=no-self-use
        """
        Get metadata field
        """
        if obj:
            return obj.json
        return None

    def get_task_name(self, obj):  # pylint: disable=no-self-use
        """
        Get the attached task name
        """
        if obj and obj.task:
            return obj.task.name
        return None
Esempio n. 2
0
class CommentSerializer(serializers.ModelSerializer):

    author = ProfileSerializer(read_only=True)
    # included_serializers = {
    #     'author': 'scholar.apps.profiles.serializers.ProfileSerializer'
    # }
    createdAt = serializers.SerializerMethodField(method_name='get_created_at')
    updatedAt = serializers.SerializerMethodField(method_name='get_updated_at')

    class Meta:
        model = Comment
        fields = (
            'id',
            'author',
            'body',
            'createdAt',
            'updatedAt',
        )

    def get_created_at(self, instance):
        return instance.created_at.isoformat()

    def get_updated_at(self, instance):
        return instance.updated_at.isoformat()

    def create(self, validated_data):
        content_object = self.context['content_object']
        author = self.context['author']

        return Comment.objects.create(
            author=author,
            content_object=content_object,
            **validated_data
        )
Esempio n. 3
0
class ForumSerializer(serializers.ModelSerializer):
    childs_forums = serializers.SerializerMethodField()
    parents_forums = serializers.SerializerMethodField()
    pending_moderations = serializers.SerializerMethodField()

    def get_childs_forums(self, obj):
        """
        Get forums childs of forum
        """
        forums = []
        for forum in obj.parents.all():
            forums.append({
                'pk': forum.pk,
                'slug': forum.slug,
                'name': forum.name
            })
        return forums

    def get_parents_forums(self, obj):
        """
        Get forums parent of forum
        """
        forums = []
        if obj:
            if not (obj.parent is None):
                parents = models.Forum.objects.raw("""
                    with recursive forums_parents as (
                        select id, parent_id, name, slug
                            from muss_forum
                            where id = """ + str(obj.pk) + """
                        union all
                        select f.id, f.parent_id, f.name, f.slug
                            from muss_forum f
                            join forums_parents p on p.parent_id = f.id
                        )
                        select * from forums_parents
                        WHERE id <> """ + str(obj.pk) + """
                        ORDER BY id;""")

                for forum in parents:
                    forums.append({
                        'pk': forum.pk,
                        'slug': forum.slug,
                        'name': forum.name
                    })
        return forums

    def get_pending_moderations(self, obj):
        """
        Check if the forum has topic pending moderations
        """
        if obj.is_moderate:
            total = obj.forums.filter(is_moderate=False).count()
            if total > 0:
                return True
        return False

    class Meta:
        model = models.Forum
        fields = '__all__'
class ExamSerializer(serializers.ModelSerializer):
    test_assignment_id = serializers.IntegerField()
    questions = serializers.SerializerMethodField()
    results = serializers.SerializerMethodField()

    class Meta:
        model = Exam
        fields = [
            'id',
            'test_assignment_id',
            'user',
            'results',
            'questions',
        ]
        read_only_fields = ['user', 'progress']

    def get_results(self, obj):
        return obj.test_results()

    def get_questions(self, obj):
        # todo serialize many questions
        serializer = QuestionSerializer(obj.test_assignment.questions.all(),
                                        many=True)

        return serializer.data

    def create(self, validated_data):
        from afi_backend.exams.api.serializers import QuestionSerializer
        # Create Exam using test_assignment_id
        test_assignment = TestAssignment.objects.get(
            id=validated_data['test_assignment_id'])
        exam = Exam.objects.create(user=self.context['request'].user,
                                   test_assignment=test_assignment)

        return exam
Esempio n. 5
0
class AntecedenteReaccionAdversaMedicamentoSerializer(
        serializers.ModelSerializer):
    familia_medicamento_nombre = serializers.SerializerMethodField()
    medicamento_nombre = serializers.SerializerMethodField()

    class Meta:
        model = AntecedenteReaccionAdversaMedicamento
        fields = (
            'uuid',
            'familia_medicamento',
            'familia_medicamento_nombre',
            'medicamento',
            'medicamento_nombre',
            'anio_diagnostico',
            'observaciones',
            'registro_antecedente',
            'consulta_paciente',
            'ciudadano',
        )

    def get_familia_medicamento_nombre(self, obj):
        # Obtener el nombre de la familia del medicamento, previamente cargado del fixture correspondiente
        return FamiliaMedicamentoAntecedenteSugerido.objects.get(
            codigo=obj.familia_medicamento).nombre

    def get_medicamento_nombre(self, obj):
        # Obtener el nombre del medicamento, previamente cargado del fixture correspondiente
        return MedicamentoAntecedenteSugerido.objects.get(
            codigo=obj.medicamento).nombre
Esempio n. 6
0
class AttachmentSerializer(serializers.ModelSerializer):

    included_serializers = {
        'user': '******',
        'ticket': 'api_v3.serializers.TicketSerializer'
    }

    file_name = serializers.SerializerMethodField()
    file_size = serializers.SerializerMethodField()
    mime_type = serializers.SerializerMethodField()
    upload = AttachmentFileField()

    class Meta:
        model = Attachment
        read_only_fields = ('user', )
        fields = ('id', 'user', 'ticket', 'upload', 'file_name', 'file_size',
                  'mime_type', 'created_at')

    def get_file_name(self, obj):
        if obj.upload:
            return os.path.basename(obj.upload.name)

    def get_file_size(self, obj):
        if obj.upload and os.path.exists(obj.upload.path):
            return obj.upload.size
        return 0

    def get_mime_type(self, obj):
        if obj.upload and os.path.exists(obj.upload.path):
            try:
                return guess_mime(obj.upload.path)
            except TypeError:
                return 'application/octet-stream'
Esempio n. 7
0
class VideoSerializer(serializers.Serializer):
    dependency_count = serializers.SerializerMethodField()
    duration = serializers.IntegerField()
    license_name = serializers.SerializerMethodField()
    license_url = serializers.SerializerMethodField()
    name = serializers.CharField(max_length=100)
    url = serializers.URLField()
    stream_url = serializers.URLField()
    image_url = serializers.URLField()
    provider_name = serializers.CharField(max_length=100)
    tags = serializers.SerializerMethodField()

    def get_dependency_count(self, obj):
        data = self.context.get(obj.id)
        if data:
            return data.get('dep_count', 0)
        return 0

    def get_license_name(self, obj):
        value = obj.license_name
        if value is None or len(value) == 0:
            return None
        return value

    def get_license_url(self, obj):
        value = obj.license_url
        if value is None or len(value) == 0:
            return None
        return value

    def get_tags(self, obj):
        sorted_categories = sorted(
            obj.categories,
            key=lambda cat: obj.categories.get(cat, 'weight', default=0))
        return ','.join([cat.name for cat in sorted_categories])
Esempio n. 8
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.fields.update({
         '🦄':
         serializers.SerializerMethodField(method_name='is_superuser'),
         '🤖':
         serializers.SerializerMethodField(method_name='is_robot'),
     })
Esempio n. 9
0
class FileSerializer(serializers.HyperlinkedModelSerializer):
    # uuid = serializers.UUIDField()
    title = serializers.CharField(source='paper.title', read_only=True)
    paper = relations.ResourceRelatedField(read_only=True)
    authors = AuthorSerializer(
        many=True, read_only=True, source='paper.authors'
    )
    createdAt = serializers.SerializerMethodField(method_name='get_created_at')
    updatedAt = serializers.SerializerMethodField(method_name='get_updated_at')
    # annotations = relations.ResourceRelatedField(many=True, read_only=True)
    annotations = relations.ResourceRelatedField(
        many=True,
        read_only=True,
        related_link_view_name='file-annotations',
        related_link_url_kwarg='file_pk',
        # self_link_view_name='file-relationships'
    )

    libraries = relations.ResourceRelatedField(many=True, read_only=True)
    included_serializers = {
        'annotations': 'scholar.apps.annotations.serializers.AnnotationSerializer',
        'libraries': 'scholar.apps.papers.serializers.LibrarySerializer',
        'paper': 'scholar.apps.papers.serializers.PaperSerializer',
    }

    def get_created_at(self, instance):
        return instance.created_at.isoformat()

    def get_updated_at(self, instance):
        return instance.updated_at.isoformat()

    # def create(self, validated_data):
    #     paper = Paper.objects.get(pk=1)
    #     file = File.objects.create(paper=paper, **validated_data)
    #     return file

    class Meta:
        model = File
        fields = (
            'id',
            'title',
            'name',
            'hash',
            'paper',
            'authors',
            'createdAt',
            'updatedAt',
            'annotations',
            'libraries'
        )
        read_only_fields = (
            'annotations',
        )

    class JSONAPIMeta:
        resource_name = 'files'
        included_resources = ['paper']
Esempio n. 10
0
 def __init__(self, *args, token=None, **kwargs):
     super(ShareUserSerializer, self).__init__(*args, **kwargs)
     if token:
         self.fields.update({
             'token': serializers.SerializerMethodField()
         })
     self.fields.update({
         '🦄': serializers.SerializerMethodField(method_name='is_superuser'),
         '🤖': serializers.SerializerMethodField(method_name='is_robot'),
     })
Esempio n. 11
0
class OwnerSerializer(serializers.ModelSerializer):
    firstname = serializers.SerializerMethodField()
    lastname = serializers.SerializerMethodField()

    class Meta:
        model = Owner
        fields = ('id', 'username', 'firstname', 'lastname', 'email')

    def get_firstname(self, obj):
        return obj.first_name

    def get_lastname(self, obj):
        return obj.last_name
Esempio n. 12
0
class NotificationSerializer(serializers.ModelSerializer):
    comment = serializers.SerializerMethodField()
    topic = serializers.SerializerMethodField()
    register = serializers.SerializerMethodField()

    def get_comment(self, obj):
        try:
            if str(obj.content_object._meta) == "muss.comment":
                return {
                    'topicid': obj.content_object.topic.pk,
                    'slug': obj.content_object.topic.slug,
                    'title': obj.content_object.topic.title,
                    'username': obj.content_object.user.username,
                    'userid': obj.content_object.user.pk
                }
            else:
                return {}
        except AttributeError:
            return {}

    def get_topic(self, obj):
        try:
            if str(obj.content_object._meta) == "muss.topic":
                return {
                    'topicid': obj.content_object.pk,
                    'slug': obj.content_object.slug,
                    'title': obj.content_object.title,
                    'username': obj.content_object.user.username,
                    'userid': obj.content_object.user.pk
                }
            else:
                return {}
        except AttributeError:
            return {}

    def get_register(self, obj):
        try:
            if str(obj.content_object._meta) == "muss.register":
                return {
                    'forumid': obj.content_object.forum.pk,
                    'slug': obj.content_object.forum.slug,
                    'forum': obj.content_object.forum.name,
                }
            else:
                return {}
        except AttributeError:
            return {}

    class Meta:
        model = models.Notification
        fields = '__all__'
Esempio n. 13
0
class BoardSiloSerializer(serializers.ModelSerializer):
    silodata = serializers.SerializerMethodField()
    createddate = serializers.SerializerMethodField()

    class Meta:
        model = Boardsilo
        fields = ('owner', 'name', 'reads', 'description', 'createddate', 'id', 'silodata','shared','tags','public')

    def get_silodata(self, obj):
        link = "/api/silo/" + str(obj.id) + "/data"
        return (self.context['request'].build_absolute_uri(link))

    def get_createddate(self, obj):
        return obj.create_date
Esempio n. 14
0
class CartSerializer(serializers.ModelSerializer):
    included_serializers = {'order_items': OrderItemSerializer}
    total = serializers.SerializerMethodField()

    class Meta:
        model = Cart
        fields = [
            'order_items',
            'is_paid',
            'created_at',
            'total',
        ]

    def get_total(self, obj):
        total = 0
        for item in obj.order_items.all():
            price = None
            if item.content_object:
                price = item.content_object.price
            if price:
                total += price

        if total:
            return total.amount
        return None
Esempio n. 15
0
class SubscriptionSerializer(serializers.ModelSerializer):
    membership_type = serializers.ChoiceField(
        choices=Membership.TIER,
        source='user_membership.membership.membership_type')
    payment_method = serializers.ChoiceField(
        choices=PaymentMethod.PAYMENT_TYPES,
        source='payment_method.payment_type',
    )
    payment_url = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = Subscription
        fields = [
            'membership_type',
            'payment_method',
            'payment_url',
        ]

    def create(self, validated_data):
        membership = validated_data.get('user_membership')
        membership_type = membership.get('membership').get('membership_type')
        user = self.context['user']

        payment_type = validated_data.get('payment_method').get('payment_type')
        payment_method = PaymentMethod.objects.get(payment_type=payment_type)

        membership_type = Membership.objects.get(
            membership_type=membership_type)
        user_membership = UserMembership.objects.create(
            membership=membership_type, user=user)
        return Subscription.objects.create(user_membership=user_membership,
                                           payment_method=payment_method)

    def get_payment_url(self, obj):
        return obj.get_payment_url()
Esempio n. 16
0
class ChangeSetSerializer(ShareModelSerializer):
    # changes = ChangeSerializer(many=True)
    change_count = serializers.SerializerMethodField()
    self = serializers.HyperlinkedIdentityField(view_name='api:changeset-detail')
    source = ShareUserSerializer(source='normalized_data.source')
    status = serializers.SerializerMethodField()

    def get_status(self, obj):
        return ChangeSet.STATUS[obj.status]

    def get_change_count(self, obj):
        return obj.changes.count()

    class Meta:
        model = models.ChangeSet
        fields = ('self', 'id', 'submitted_at', 'change_count', 'source', 'status')
class CommentSerializer(serializers.ModelSerializer):
    # testing remapping of related name
    writer = relations.ResourceRelatedField(source="author", read_only=True)
    modified_days_ago = serializers.SerializerMethodField()

    included_serializers = {
        "entry": EntrySerializer,
        "author": AuthorSerializer,
        "writer": WriterSerializer,
    }

    class Meta:
        model = Comment
        exclude = (
            "created_at",
            "modified_at",
        )
        # fields = ('entry', 'body', 'author',)
        meta_fields = ("modified_days_ago",)

    class JSONAPIMeta:
        included_resources = ("writer",)

    def get_modified_days_ago(self, obj):
        return (datetime.now() - obj.modified_at).days
Esempio n. 18
0
class UserSerializer(serializers.ModelSerializer):
    # For profile relation
    user = SerializerMethodResourceRelatedField(many=False, read_only=True)
    user_photo = serializers.SerializerMethodField()

    def get_user_photo(self, obj):
        """
        Get photo profile topic user
        """
        return utils.get_photo_profile(obj)

    def create(self, validated_data):
        User = get_user_model()

        # Check if exists the email
        user = User.objects.filter(email=validated_data['email'])
        if user:
            raise serializers.ValidationError(_("The email already exists."))

        user = User(
            email=validated_data['email'],
            username=validated_data['username'],
            first_name=validated_data['first_name'],
            last_name=validated_data['last_name'],
        )
        user.is_active = False
        user.set_password(validated_data['password'])
        user.save()
        return user

    class Meta:
        model = get_user_model()
        fields = '__all__'
        extra_kwargs = {'password': {'write_only': True}}
Esempio n. 19
0
class EthActionSerializer(serializers.ModelSerializer):
    transaction = serializers.ResourceRelatedField(
        queryset=Transaction.objects.all())
    transaction_receipt = serializers.ResourceRelatedField(
        source='transactionreceipt', queryset=TransactionReceipt.objects.all())
    explorer_hash = serializers.SerializerMethodField()

    class Meta:
        model = EthAction
        fields = '__all__'

    included_serializers = {
        'transaction': TransactionSerializer,
        'transaction_receipt': TransactionReceiptSerializer,
        'async_job': AsyncJobSerializer,
        'shipment': FKShipmentSerializer
    }

    class JSONAPIMeta:
        included_resources = [
            'transaction', 'transaction_receipt', 'async_job'
        ]

    def get_explorer_hash(self, obj):
        if hasattr(obj, 'transactionreceipt'):
            return obj.transactionreceipt.evm_hash or obj.transaction_hash
        return None
Esempio n. 20
0
class SessionSerializer(BaseSessionSerializer):
    """Tennis session serializer."""

    trainings = resource_related_field(
        Training,
        'session',
        'trainings',
        namespace='tennis',
    )

    players = resource_related_field(
        Player,
        'session',
        'players',
        namespace='tennis',
    )

    matches = resource_related_field(
        Match,
        'session',
        'matches',
        namespace='tennis',
    )

    exchanges = resource_related_field(
        Exchange,
        'session',
        'exchanges',
        namespace='tennis',
    )

    included_serializers = {
        **BaseSessionSerializer.included_serializers,
        'trainings': 'tennis.serializers.TrainingSerializer',
        'players': 'tennis.serializers.PlayerSerializer',
        'matches': 'tennis.serializers.MatchSerializer',
        'exchanges': 'tennis.serializers.ExchangeSerializer',
        'videos': 'tennis.serializers.VideoSerializer',
    }

    label = serializers.SerializerMethodField()

    def get_label(self, obj):
        """Serialize session label."""
        return 'Session'

    class Meta(BaseSessionSerializer.Meta):
        """SessionSerializer Meta class."""

        fields = BaseSessionSerializer.Meta.fields + (
            'id',
            'date',
            'place',
            'duration',
            'trainings',
            'matches',
            'players',
            'label',
            'exchanges',
        )
Esempio n. 21
0
class ShipmentImportSerializer(S3PreSignedMixin, EnumSupportSerializerMixin,
                               serializers.ModelSerializer):
    file_type = UpperEnumField(FileType,
                               lenient=True,
                               read_only=True,
                               ints_as_names=True)
    upload_status = UpperEnumField(UploadStatus,
                                   lenient=True,
                                   ints_as_names=True)
    processing_status = UpperEnumField(ProcessingStatus,
                                       lenient=True,
                                       ints_as_names=True)
    presigned_s3 = serializers.SerializerMethodField()
    _s3_bucket = settings.SHIPMENT_IMPORTS_BUCKET

    class Meta:
        model = ShipmentImport
        exclude = (
            'owner_id',
            'masquerade_id',
        )
        read_only_fields = (
            'storage_credentials_id',
            'shipper_wallet_id',
            'carrier_wallet_id',
        )
        meta_fields = ('presigned_s3', )

    def get_presigned_s3(self, obj):
        if obj.upload_status != UploadStatus.COMPLETE:
            return super(ShipmentImportSerializer, self).get_presigned_s3(obj)
        return None
class ChartSerializer(serializers.ModelSerializer):
    permissions = DRYPermissionsField()
    image_id = serializers.SerializerMethodField()

    def get_image_id(self, obj):
        if obj.image:
            return obj.image.name
        else:
            return 'missing_image'

    class Meta:
        model = Chart
        fields = (
            'id',
            'url',
            'status',
            'title',
            'arrangers',
            'composers',
            'lyricists',
            'description',
            'notes',
            'image',
            'image_id',
            'holders',
            'repertories',
            # 'songs',
            'permissions',
        )
Esempio n. 23
0
class AntecedenteFamiliarCiudadanoSerializer(serializers.ModelSerializer):
    parentesco = serializers.ListField()
    parentesco_display = serializers.SerializerMethodField()

    class Meta:
        model = AntecedenteFamiliar
        fields = (
            'uuid',
            'ciex',
            'ciex_descripcion',
            'ciudadano',
            'codigo_antecedente_sugerido',
            'consulta_paciente',
            'es_removido',
            'fecha_fin',
            'fecha_inicio',
            'grupo_antecedente',
            'nombre_antecedente_sugerido',
            'observaciones',
            'parentesco',
            'parentesco_display',
            'registro_antecedente',
            'subgrupo_antecedente',
        )

    def get_parentesco_display(self, obj):
        parentescos = []
        for parentesco in obj.parentesco:
            parentescos.append(PARENTESCO_CHOICES_DICT.get(str(parentesco)))
        return parentescos
Esempio n. 24
0
class TicketSerializer(serializers.ModelSerializer):
    id = serializers.CharField()
    activation_link = serializers.SerializerMethodField()
    scanned = serializers.BooleanField(read_only=True)
    included_serializers = {
        'offline_lecture': OfflineLectureSerializer,
    }
    customer_email = serializers.EmailField(source='customer.email')
    offline_lecture_id = serializers.CharField(source='offline_lecture.id')
    offline_lecture = serializers.ResourceRelatedField(read_only=True)

    class Meta:
        model = Ticket
        fields = [
            'id',
            'customer_email',
            'activation_link',
            'offline_lecture',
            'scanned',
            'offline_lecture_id',
        ]

    def get_activation_link(self, obj):
        if obj.get_qr_code():
            return f"{settings.SITE_URL}/api/tickets/activate/{obj.qrcode.code}"
        return ""

    def create(self, validated_data):
        customer = validated_data.get('customer')
        offline_lecture = validated_data.get('offline_lecture')
        customer = User.objects.get(email=customer.get('email'))
        offline_lecture = OfflineLecture.objects.get(
            id=offline_lecture.get('id'))
        return Ticket.objects.create(customer=customer,
                                     offline_lecture=offline_lecture)
Esempio n. 25
0
class ShipmentSerializer(FieldPermissionSerializerMixin, EnumSupportSerializerMixin, serializers.ModelSerializer):
    """
    Serializer for a shipment object
    """
    load_data = LoadShipmentSerializer(source='loadshipment', required=False)

    geofences = GeofenceListField(child=serializers.CharField(), required=False)

    state = UpperEnumField(TransitState, lenient=True, ints_as_names=True, required=False, read_only=True)
    exception = UpperEnumField(ExceptionType, lenient=True, ints_as_names=True, required=False)
    gtx_validation = UpperEnumField(GTXValidation, lenient=True, ints_as_names=True, required=False)
    tags = PermissionResourceRelatedField(many=True, required=False, read_only=True, source='shipment_tags',
                                          permission_classes=(AccessRequest.related_field_permission(
                                              Endpoints.tags, PermissionLevel.READ_ONLY)(),))

    permission_derivation = serializers.SerializerMethodField()

    included_serializers = {
        'ship_from_location': LocationSerializer,
        'ship_to_location': LocationSerializer,
        'bill_to_location': LocationSerializer,
        'final_destination_location': LocationSerializer,
        'load_data': LoadShipmentSerializer,
        'device': DeviceSerializer,
        'tags': ShipmentTagSerializer,
    }

    class Meta:
        model = Shipment
        exclude = ('version', 'background_data_hash_interval', 'manual_update_hash_interval', 'asset_physical_id')
        read_only_fields = ('owner_id', 'contract_version', 'arrival_est', 'carrier_abbv') \
            if settings.PROFILES_ENABLED else ('contract_version', 'arrival_est', 'carrier_abbv')
        meta_fields = ('permission_derivation',)

    class JSONAPIMeta:
        included_resources = ['ship_from_location', 'ship_to_location', 'bill_to_location',
                              'final_destination_location', 'load_data', 'tags', ]

    @property
    def user(self):
        return self.context['request'].user

    @property
    def auth(self):
        return get_jwt_from_request(self.context['request'])

    def validate_geofences(self, geofences):
        for geofence in geofences:
            if not validate_uuid4(geofence):
                raise serializers.ValidationError(f'Invalid UUIDv4 {geofence} provided in Geofences')

        # Deduplicate list
        return list(set(geofences))

    def get_permission_derivation(self, obj):
        if ('request' in self.context and
                obj.id in getattr(self.context['request'].user, 'access_request_shipments', [])):
            return 'AccessRequest'
        return 'OwnerOrPartyOrPermissionLink'
Esempio n. 26
0
class CiudadanoRNSerializer(serializers.ModelSerializer):
    dni_ciudadano = serializers.SerializerMethodField('get_dni')
    nombres_ciudadano = serializers.SerializerMethodField('get_nombres')
    apellido_paterno_ciudadano = serializers.SerializerMethodField(
        'get_apellido_paterno')
    apellido_materno_ciudadano = serializers.SerializerMethodField(
        'get_apellido_materno')

    class Meta:
        model = CiudadanoRN
        fields = [
            'uuid', 'uid', 'cui', 'tipo_doc_madre', 'numero_doc_madre',
            'primer_apellido_madre', 'segundo_apellido_madre',
            'prenombres_madre', 'sexo_nacido', 'fecha_nacimiento',
            'hora_nacimiento', 'peso_nacido', 'talla_nacido',
            'apgar_uno_nacido', 'apgar_cinco_nacido',
            'numero_nacido_perim_cefalico', 'numero_nacido_perim_toracico',
            'numero_temperatura', 'resultado_examen_fisico',
            'edad_examen_fisico', 'unida_medida_edad', 'duracion_parto',
            'atiende_parto', 'condicion_parto', 'tipo_parto',
            'financiador_parto', 'posicion_parto', 'es_partograma',
            'duracion_parto', 'es_episiotomia_parto', 'alumbramiento_parto',
            'desgarro_parto', 'placenta_parto', 'es_eess_procedencia',
            'eess_procedencia', 'etnia_nacido', 'dni_ciudadano',
            'nombres_ciudadano', 'apellido_paterno_ciudadano',
            'apellido_materno_ciudadano', 'codigo_local', 'codigo_renaes',
            'ciudadano_uuid', 'ciudadano_tipo_doc', 'ciudadano_numero_doc',
            'es_ficha_activa', 'codigo_renaes_adscrito',
            'duracion_semanas_parto'
        ]

    def get_dni(self, obj):
        num_doc = obj.ciudadano.numero_documento
        return num_doc

    def get_nombres(self, obj):
        nombres = obj.ciudadano.nombres
        return nombres

    def get_apellido_paterno(self, obj):
        apellido_paterno = obj.ciudadano.apellido_paterno
        return apellido_paterno

    def get_apellido_materno(self, obj):
        apellido_materno = obj.ciudadano.apellido_materno
        return apellido_materno
Esempio n. 27
0
class CountrySerializer(serializers.ModelSerializer):
    iso2 = serializers.SerializerMethodField()

    class Meta:
        model = Country
        fields = ('id', 'name', 'iso2')

    def get_iso2(self, obj):
        return obj.iso_two_letters_code
Esempio n. 28
0
class UserSerializer(serializers.ModelSerializer):
    name = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ('id', 'username', 'email', 'name', 'groups')

    def get_name(self, obj):
        return "%s %s" % (obj.first_name, obj.last_name)
Esempio n. 29
0
class SiteBannerSerializer(ShareModelSerializer):
    color = serializers.SerializerMethodField()

    def get_color(self, obj):
        return SiteBanner.COLOR[obj.color]

    class Meta:
        model = models.SiteBanner
        fields = ('title', 'description', 'color', 'icon')
Esempio n. 30
0
class MembershipField(relations.ResourceRelatedField):
    membership_type = serializers.SerializerMethodField()

    class Meta:
        model = Membership
        fields = ['membership_type', 'price']

    def get_membership_type(self, obj):
        return obj.get_membership_type_display()