Ejemplo n.º 1
0
class ThesisBaseSerializer(ModelSerializer):
    state_label = CharField(source='get_state_display', read_only=True)

    authors = UserSerializer(read_only=True, many=True)

    supervisor = UserSerializer(read_only=True)
    opponent = UserSerializer(read_only=True)

    supervisor_id = PrimaryKeyRelatedField(
        write_only=True, source='supervisor', allow_null=True, required=False,
        queryset=User.school_users.teachers(),
    )
    opponent_id = PrimaryKeyRelatedField(
        write_only=True, source='opponent', allow_null=True, required=False,
        queryset=User.school_users.teachers()
    )

    class Meta:
        model = Thesis
        fields = (
            'id',
            'title',
            'abstract',
            'state',
            'state_label',

            'authors',
            'supervisor',
            'supervisor_id',
            'opponent',
            'opponent_id',
        )
Ejemplo n.º 2
0
 def to_internal_value(self, data):
     """Resolve the version only by `id`."""
     # Version queryset is unfiltered, the version is checked more
     # thoroughly in `RatingSerializer.validate()` method.
     field = PrimaryKeyRelatedField(queryset=Version.unfiltered)
     value = field.to_internal_value(data)
     return OrderedDict([('id', data), ('version', value)])
Ejemplo n.º 3
0
class CheckoutSerializer(serializers.Serializer):
    payment_method = PrimaryKeyRelatedField(
        queryset=PaymentMethod.objects.all())
    shipping_method = PrimaryKeyRelatedField(
        queryset=PaymentMethod.objects.all())
    shipping_address = AddressSerializer()
    billing_address = AddressSerializer()
Ejemplo n.º 4
0
class BannerSerializer(serializers.ModelSerializer):
    book = PrimaryKeyRelatedField(read_only=True)
    topic = PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = Banner
        fields = ('name', 'desc', 'img', 'type', 'book', 'topic', 'url')
Ejemplo n.º 5
0
class UserSerializerWithMoment(ModelSerializer):
    moments = PrimaryKeyRelatedField(many=True, read_only=True)
    comments = PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = LowUserModel
        fields = '__all__'
Ejemplo n.º 6
0
class AttachmentSerializer(ModelSerializer):
    type_attachment = TypeAttachmentSerializer(read_only=True)
    type_attachment_id = PrimaryKeyRelatedField(
        write_only=True, source='type_attachment',
        queryset=TypeAttachment.objects.all(),
    )

    thesis_id = PrimaryKeyRelatedField(
        write_only=True, source='thesis',
        queryset=Thesis.objects.all(),
    )

    url = HyperlinkedIdentityField(view_name='api:v1:attachment-detail')

    class Meta:
        model = Attachment
        fields = (
            'id',
            'type_attachment',
            'type_attachment_id',
            'url',
            'content_type',
            'size_label',
            'thesis_id',
        )
        read_only_fields = ('content_type',)
Ejemplo n.º 7
0
class StatisticMapSerializer(ImageSerializer):

    cognitive_paradigm_cogatlas = StringRelatedField(read_only=True)
    cognitive_paradigm_cogatlas_id = PrimaryKeyRelatedField(
        read_only=True, source="cognitive_paradigm_cogatlas")
    cognitive_contrast_cogatlas = StringRelatedField(read_only=True)
    cognitive_contrast_cogatlas_id = PrimaryKeyRelatedField(
        read_only=True, source="cognitive_contrast_cogatlas")
    map_type = serializers.SerializerMethodField()
    analysis_level = serializers.SerializerMethodField()

    def get_map_type(self, obj):
        return obj.get_map_type_display()

    def get_analysis_level(self, obj):
        return obj.get_analysis_level_display()

    class Meta:
        model = StatisticMap
        exclude = ['polymorphic_ctype', 'ignore_file_warning', 'data']

    def value_to_python(self, value):
        if not value:
            return value
        try:
            return json.loads(value)
        except (TypeError, ValueError):
            return value

    def to_representation(self, obj):
        ret = super(ImageSerializer, self).to_representation(obj)
        for field_name, value in obj.data.items():
            if field_name not in ret:
                ret[field_name] = self.value_to_python(value)
        return ret
Ejemplo n.º 8
0
class OrganizationUpdateSerializer(serializers.ModelSerializer):
    """
    Update Serializer for Organization
    """
    organization_address = OrganizationAddressSerializer(allow_null=True)
    actions_type = PrimaryKeyRelatedField(
        queryset=OrganizationActionsType.objects.all())
    status = PrimaryKeyRelatedField(queryset=OrganizationStatus.objects.all())
    type = PrimaryKeyRelatedField(queryset=OrganizationType.objects.all())

    def update(self, obj, validated_data):
        Organization.objects.filter(id=obj.id).update(
            name=validated_data['name'],
            actions_type=validated_data['actions_type'],
            status=validated_data['status'],
            update_timestamp=timezone.now())

        addr = validated_data.pop('organization_address')

        OrganizationAddress.objects.filter(organization_id=obj.id).delete()
        OrganizationAddress.objects.create(organization=obj,
                                           primary=True,
                                           **addr)
        return obj

    class Meta:
        model = Organization
        fields = ('id', 'name', 'type', 'status', 'actions_type',
                  'organization_address', 'update_timestamp')
        read_only_fields = ('id', 'type')
Ejemplo n.º 9
0
 def to_internal_value(self, data):
     """Resolve the version only by `id`."""
     # Version queryset is unfiltered, the version is checked more
     # thoroughly in `RatingSerializer.validate()` method.
     field = PrimaryKeyRelatedField(queryset=Version.unfiltered)
     value = field.to_internal_value(data)
     return OrderedDict([('id', data), ('version', value)])
Ejemplo n.º 10
0
class RoleSerializer(serializers.ModelSerializer):
    permissions = PrimaryKeyRelatedField(queryset=Permission.objects.all(),
                                         many=True,
                                         required=False)
    organisation = PrimaryKeyRelatedField(queryset=Organisation.objects.all(),
                                          required=False,
                                          allow_null=True)
    type = serializers.ChoiceField(choices=UserType.non_system_choices())
    name = serializers.CharField(
        max_length=30,
        error_messages={"blank": strings.Roles.BLANK_NAME},
    )
    statuses = PrimaryKeyRelatedSerializerField(
        queryset=CaseStatus.objects.all(),
        many=True,
        required=False,
        serializer=CaseStatusSerializer)

    class Meta:
        model = Role
        fields = (
            "id",
            "name",
            "permissions",
            "type",
            "organisation",
            "statuses",
        )
Ejemplo n.º 11
0
class ClaimCreateSerializer(serializers.ModelSerializer):
    topics = PrimaryKeyRelatedField(many=True, queryset=Topic.objects.all())
    source_of_claim = SourceCreateSerializer()
    claimants = PrimaryKeyRelatedField(many=True,
                                       write_only=True,
                                       queryset=Entity.objects.all())

    class Meta:
        model = Claim
        fields = [
            'id', 'claim_text', 'description', 'topics', 'source_of_claim',
            'claimants'
        ]

    def create(self, validated_data):
        source_data = validated_data.pop('source_of_claim')
        authors = source_data.pop('authors')
        source_instance = Source.objects.create(**source_data)
        source_instance.authors.set(authors)
        user = validated_data.pop('user')
        topics = validated_data.pop('topics')
        claimants = validated_data.pop('claimants')
        claim_instance = Claim.objects.create(**validated_data,
                                              source_of_claim=source_instance,
                                              submitted_by=user)
        claim_instance.topics.set(topics)
        claim_instance.claimants.set(claimants)
        claim_instance.save()
        return claim_instance
Ejemplo n.º 12
0
class TraceSerializer(serializers.ModelSerializer):
    """
    Serializer for traces with contains vastly different internal and external models.
    Internal model specifies both artifact name and type for both source and target.
    External model specifies only the ids of source and target artifacts.
    """
    source = PrimaryKeyRelatedField(queryset=models.Artifact.objects.all())
    target = PrimaryKeyRelatedField(queryset=models.Artifact.objects.all())

    class Meta:
        """
        Specifies the internal model used by serializer and
        external fields that should be parsed.
        """
        model = models.Trace
        fields = ['source', 'target']

    def to_internal_value(self, data):
        """
        Given data containing artifact type and name for source and target artifacts,
        looks up each artifact and creates trace referencing both. Note,
        relies on the fact that artifacts already exist in persistent memory.
        """
        project_id = data.get('project')

        def validate_trace_artifact(t_type):
            """
            given type, source or target, validates and returns the artifact referenced
            errors on:
            - unknown artifact type
            - artifact with type and name not found inside project
            """
            def apply_filter(queryset, f_kwargs):
                """
                Iteratively applies key-value pairs in f_kwargs to queryset.filter, returning result.
                """
                filter_queryset = queryset
                for filter_key, filter_value in f_kwargs.items():
                    filter_item = {filter_key: filter_value}
                    filter_queryset = filter_queryset.filter(**filter_item)
                    if filter_queryset.count() == 0:
                        raise ValidationError(
                            create_trace_error(t_type, filter_key,
                                               filter_value))
                return filter_queryset

            a_type, a_name = data.get("%s_type" % t_type), data.get("%s_name" %
                                                                    t_type)
            a_queryset = apply_filter(models.Artifact.objects, {
                'project_id': project_id,
                'type': a_type,
                'name': a_name
            })

            return a_queryset.first()

        source = validate_trace_artifact("source")
        target = validate_trace_artifact("target")

        return {"source": source, "target": target}
Ejemplo n.º 13
0
class QuerySerializer(AmCATModelSerializer):
    user = PrimaryKeyRelatedField(read_only=True)
    project = PrimaryKeyRelatedField(read_only=True)
    parameters = ParametersField()

    class Meta:
        model = Query
Ejemplo n.º 14
0
class UserCreateSerializer(serializers.ModelSerializer):
    """
    Serializer for user creation via API
    """
    organization = PrimaryKeyRelatedField(queryset=Organization.objects.all())
    roles = PrimaryKeyRelatedField(queryset=Role.objects.all(), many=True)
    id = serializers.ReadOnlyField()

    def validate(self, data):
        data['display_name'] = '{} {}'.format(data['first_name'],
                                              data['last_name'])
        return data

    def create(self, validated_data):
        roles = validated_data.pop('roles')
        organization = validated_data.pop('organization')

        user = User.objects.create(**validated_data)
        user.organization = organization
        user.save()
        for role in roles:
            UserRole.objects.create(user=user, role=role)

        return user

    class Meta:
        model = User
        fields = ('first_name', 'last_name', 'email', 'username',
                  'display_name', 'id', 'organization', 'roles',
                  'is_government_user')
Ejemplo n.º 15
0
class JobSupplySerializer(WritableNestedModelSerializer):
    supplier_type = PrimaryKeyRelatedField(
        many=False,
        read_only=False,
        allow_null=True,
        queryset=models.CodeSupplierType.objects.all())
    supplier = PrimaryKeyRelatedField(
        many=False,
        read_only=False,
        allow_null=True,
        queryset=models.CodeSupplier.objects.all())
    book_time = PrimaryKeyRelatedField(
        many=False,
        read_only=False,
        allow_null=True,
        queryset=models.CodeTimeOfDay.objects.all())

    class Meta:
        model = models.JobSupply
        fields = (
            'pk',
            'id',
            'supplier_type',
            'supplier',
            'book_date',
            'book_time',
            'booking_number',
        )
        depth = 10
Ejemplo n.º 16
0
class HmrcQueryCreateSerializer(serializers.ModelSerializer):
    organisation = PrimaryKeyRelatedField(queryset=Organisation.objects.all())
    hmrc_organisation = PrimaryKeyRelatedField(queryset=Organisation.objects.all())
    case_type = PrimaryKeyRelatedField(
        queryset=CaseType.objects.all(), error_messages={"required": strings.Applications.Generic.NO_LICENCE_TYPE},
    )

    def __init__(self, case_type_id, **kwargs):
        super().__init__(**kwargs)

        if self.context.type != OrganisationType.HMRC:
            raise exceptions.PermissionDenied("User does not belong to an HMRC organisation")

        self.initial_data["case_type"] = case_type_id
        self.initial_data["hmrc_organisation"] = self.context.id
        self.initial_data["status"] = get_case_status_by_status(CaseStatusEnum.DRAFT).id

    class Meta:
        model = HmrcQuery
        fields = (
            "name",
            "reasoning",
            "case_type",
            "organisation",
            "hmrc_organisation",
            "status",
        )
Ejemplo n.º 17
0
class AnnotationSerializer(ModelSerializer):

    organization = OrganizationSerializer(read_only=True)
    platform = PlatformSerializer(read_only=True)
    subject = ReadOnlyField()
    organization_id = PrimaryKeyRelatedField(
        source='organization',
        write_only=True,
        allow_null=True,
        queryset=Organization.objects.all())
    platform_id = PrimaryKeyRelatedField(source='platform',
                                         write_only=True,
                                         allow_null=True,
                                         queryset=Platform.objects.all())
    can_edit = BooleanField(read_only=True)
    submitter = HiddenField(default=CurrentUserDefault())

    class Meta:
        model = Annotation
        fields = ('pk', 'organization_id', 'platform_id', 'subject',
                  'subject_en', 'subject_cs', 'short_message',
                  'short_message_en', 'short_message_cs', 'message',
                  'message_en', 'message_cs', 'start_date', 'end_date',
                  'organization', 'platform', 'level', 'can_edit', 'submitter')
        extra_kwargs = {
            'subject_en': {
                'allow_blank': False
            },
            'subject_cs': {
                'allow_blank': False
            },
        }

    def update(self, instance: Annotation, validated_data):
        # in patch updates, the submitter field might not be present
        submitter = validated_data.pop('submitter',
                                       None) or self.context['request'].user
        if not instance.can_edit(submitter):
            raise PermissionDenied(
                'User is not allowed to edit this object - it is locked.')
        result = super().update(instance, validated_data)  # type: Annotation
        return self._adjust_permissions(result, submitter)

    def create(self, validated_data):
        submitter = validated_data.pop('submitter')  # type: User
        result = super().create(validated_data)
        return self._adjust_permissions(result, submitter)

    @classmethod
    def _adjust_permissions(cls, instance: Annotation, submitter: User):
        instance.author = submitter
        instance.owner_level = submitter.organization_relationship(instance.organization_id) \
            if instance.organization_id else UL_CONS_STAFF
        # we do not want to set the level too high in order for the staff to be able to edit it
        if instance.owner_level > UL_CONS_STAFF:
            instance.owner_level = UL_CONS_STAFF
        instance.save()
        instance.can_edit = instance.can_edit(submitter)
        return instance
class CaravaggioOrganizationSerializerV1(DynamicFieldsSerializer):
    """
    CaravaggioClientSerializerV1 defines the API representation of the
     CaravaggioClient.
    """

    client = PrimaryKeyRelatedField(queryset=CaravaggioClient.objects.all(),
                                    required=True)

    owner = PrimaryKeyRelatedField(queryset=CaravaggioUser.objects.all(),
                                   required=True)

    administrators = PrimaryKeyRelatedField(
        queryset=CaravaggioUser.objects.all(), many=True, required=False)

    members = PrimaryKeyRelatedField(queryset=CaravaggioUser.objects.all(),
                                     many=True,
                                     required=False)

    restricted_members = PrimaryKeyRelatedField(
        queryset=CaravaggioUser.objects.all(), many=True, required=False)

    class Meta:
        model = CaravaggioOrganization
        fields = (
            "id",
            "client",
            "email",
            "name",
            "owner",
            "administrators",
            "members",
            "restricted_members",
            "number_of_total_members",
            "number_of_members",
            "number_of_administrators",
            "number_of_restricted_members",
            "all_members",
            "is_active",
            "date_deactivated",
            "created",
            "updated",
        )
        read_only_fields = (
            "id",
            "client",
            "created",
            "updated",
            "members",
            "restricted_members",
            "date_deactivated",
            "administrators",
            "members",
            "restricted_members",
            "number_of_total_members",
            "number_of_members",
            "number_of_administrators",
            "number_of_restricted_members",
        )
Ejemplo n.º 19
0
class BookingSerializer(serializers.ModelSerializer):
    customer = PrimaryKeyRelatedField(read_only=True)
    driver = PrimaryKeyRelatedField(read_only=True)
    status = serializers.IntegerField(default=0)

    class Meta:
        model = Booking
        fields = ('id', 'customer', 'driver', 'status')
Ejemplo n.º 20
0
 def __init__(self, *args, **kwargs):
     super(CartItemSerializer, self).__init__(*args, **kwargs)
     user = self.context['request'].user
     # overriding field to Browsable API show only user's cart in option
     self.fields['cart'] = PrimaryKeyRelatedField(
         queryset=Cart.objects.filter(owner=user), required=True)
     self.fields['product'] = PrimaryKeyRelatedField(
         queryset=Product.objects.filter(visible=True), required=True)
Ejemplo n.º 21
0
class StageCreateSerializer(serializers.ModelSerializer):
    action = PrimaryKeyRelatedField(queryset=Action.objects.all())
    owner = PrimaryKeyRelatedField(queryset=Owner.objects.all())
    sample = PrimaryKeyRelatedField(queryset=Sample.objects.all())

    class Meta:
        model = Stage
        fields = ['action', 'sample', 'owner']
Ejemplo n.º 22
0
class ComplexMeasurementSerializer(serializers.HyperlinkedModelSerializer):
    sensor = PrimaryKeyRelatedField(queryset=Sensor.objects.all(),
                                    required=False)
    owner = PrimaryKeyRelatedField(queryset=User.objects.all(), required=False)

    class Meta:
        model = ComplexMeasurement
        fields = ('id', 'sensor', 'name', 'begin', 'end', 'time_window',
                  'frequency', 'owner')
Ejemplo n.º 23
0
class SushiCredentialsSerializer(ModelSerializer):

    organization = OrganizationSerializer(read_only=True)
    platform = PlatformSerializer(read_only=True)
    active_counter_reports_long = \
        CounterReportTypeSerializer(many=True, source='active_counter_reports', read_only=True)
    organization_id = PrimaryKeyRelatedField(
        source='organization',
        write_only=True,
        queryset=Organization.objects.all())
    platform_id = PrimaryKeyRelatedField(source='platform',
                                         write_only=True,
                                         queryset=Platform.objects.all())
    locked_for_me = BooleanField(read_only=True)
    can_lock = BooleanField(read_only=True)
    submitter = HiddenField(default=CurrentUserDefault())
    locked = SerializerMethodField()

    class Meta:
        model = SushiCredentials
        fields = ('pk', 'organization', 'platform', 'enabled', 'url',
                  'counter_version', 'requestor_id', 'customer_id',
                  'http_username', 'http_password', 'api_key', 'extra_params',
                  'active_counter_reports', 'active_counter_reports_long',
                  'organization_id', 'platform_id', 'submitter',
                  'locked_for_me', 'lock_level', 'can_lock', 'locked',
                  'outside_consortium')

    def get_locked(self, obj: SushiCredentials):
        return obj.lock_level >= UL_CONS_STAFF

    def update(self, instance: SushiCredentials, validated_data):
        submitter = validated_data.pop('submitter',
                                       None) or self.context['request'].user
        if not instance.can_edit(submitter):
            raise PermissionDenied(
                'User is not allowed to edit this object - it is locked.')
        result = super().update(instance,
                                validated_data)  # type: SushiCredentials
        result.last_updated_by = submitter
        result.save()
        submitter_level = submitter.organization_relationship(
            result.organization_id)
        result.can_lock = submitter_level >= UL_CONS_STAFF
        result.locked_for_me = submitter_level < result.lock_level
        return result

    def create(self, validated_data):
        submitter = validated_data.pop('submitter')
        result = super().create(validated_data)
        result.last_updated_by = submitter
        result.save()
        submitter_level = submitter.organization_relationship(
            result.organization_id)
        result.can_lock = submitter_level >= UL_CONS_STAFF
        result.locked_for_me = submitter_level < result.lock_level
        return result
Ejemplo n.º 24
0
class CreateLoanSerializer(serializers.ModelSerializer):
    """Only serialize the loanable and the user."""

    loanable = PrimaryKeyRelatedField(queryset=Loanable.objects.all())
    user = PrimaryKeyRelatedField(queryset=User.objects.all())

    class Meta:
        model = Loan
        fields = ("loanable", "user")
class ComentarioSerializer(ModelSerializer):
    user = PrimaryKeyRelatedField(many=False, queryset=User.objects.all())
    point = PrimaryKeyRelatedField(many=False,
                                   queryset=PontoTuristico.objects.all())

    class Meta:
        model = Comentario
        fields = ('id', 'user', 'point', 'comment', 'approved', 'created_at',
                  'updated_at')
Ejemplo n.º 26
0
class ViewRequestSerializer(serializers.ModelSerializer):
    patient = PrimaryKeyRelatedField(required=False, queryset=Patient.objects)
    business_user = PrimaryKeyRelatedField(
        required=False, queryset=AbstractBusinessUser.objects)
    allowed = BooleanField(required=True)

    class Meta:
        depth = 2
        model = ViewRequest
        fields = ['patient', 'business_user', 'allowed']
Ejemplo n.º 27
0
class SourceCreateSerializer(SourceCreateOrUpdateSerializer):
    type = CharField(source='resource_type', read_only=True)
    uuid = CharField(source='id', read_only=True)
    id = CharField(required=True,
                   validators=[RegexValidator(regex=NAMESPACE_REGEX)],
                   source='mnemonic')
    short_code = CharField(source='mnemonic', read_only=True)
    name = CharField(required=True)
    full_name = CharField(required=False)
    description = CharField(required=False, allow_blank=True)
    source_type = CharField(required=False, allow_blank=True)
    custom_validation_schema = CharField(required=False,
                                         allow_blank=True,
                                         allow_null=True)
    public_access = ChoiceField(required=False, choices=ACCESS_TYPE_CHOICES)
    default_locale = CharField(required=False, allow_blank=True)
    supported_locales = ListField(required=False, allow_empty=True)
    website = CharField(required=False, allow_blank=True)
    url = CharField(read_only=True)
    canonical_url = CharField(required=False,
                              allow_null=True,
                              allow_blank=True)
    versions_url = CharField(read_only=True)
    concepts_url = CharField(read_only=True)
    mappings_url = CharField(read_only=True)
    owner = CharField(source='parent_resource', read_only=True)
    owner_type = CharField(source='parent_resource_type', read_only=True)
    owner_url = CharField(source='parent_url', read_only=True)
    versions = IntegerField(source='num_versions', read_only=True)
    created_on = DateTimeField(source='created_at', read_only=True)
    updated_on = DateTimeField(source='updated_at', read_only=True)
    created_by = CharField(source='owner', read_only=True)
    updated_by = CharField(read_only=True)
    extras = JSONField(required=False, allow_null=True)
    external_id = CharField(required=False, allow_blank=True)
    user_id = PrimaryKeyRelatedField(required=False,
                                     queryset=UserProfile.objects.all(),
                                     allow_null=True)
    organization_id = PrimaryKeyRelatedField(
        required=False, queryset=Organization.objects.all(), allow_null=True)
    version = CharField(default=HEAD)

    def create(self, validated_data):
        source = self.prepare_object(validated_data)
        user = self.context['request'].user
        errors = Source.persist_new(source, user)
        self._errors.update(errors)
        return source

    def create_version(self, validated_data):
        source = self.prepare_object(validated_data)
        user = self.context['request'].user
        errors = Source.persist_new_version(source, user)
        self._errors.update(errors)
        return source
Ejemplo n.º 28
0
class ThirdPartyAppInstallSerializer(serializers.ModelSerializer):
    workspace_id = PrimaryKeyRelatedField(queryset=Workspace.objects.all(), source='workspace', write_only=True)
    workspace = WorkspaceSerializer(read_only=True)
    user_id = PrimaryKeyRelatedField(queryset=User.objects.all(), source='user', write_only=True)
    user = UserSerializer(read_only=True)
    tpa_id = PrimaryKeyRelatedField(queryset=ThirdPartyApp.objects.all(), source='tpa', write_only=True)
    tpa = ThirdPartyAppSerializer(read_only=True)

    class Meta:
        model = ThirdPartyApp
        fields = ['id', 'workspace_id', 'workspace', 'user_id', 'user', 'tpa_id', 'tpa']
Ejemplo n.º 29
0
class ExternalLocationOnApplicationSerializer(serializers.ModelSerializer):
    application = PrimaryKeyRelatedField(queryset=BaseApplication.objects.all())
    external_location = PrimaryKeyRelatedField(queryset=ExternalLocation.objects.all())

    class Meta:
        model = ExternalLocationOnApplication
        fields = (
            "id",
            "external_location",
            "application",
        )
class BattleSerializer(serializers.ModelSerializer):
    tournament = PrimaryKeyRelatedField(queryset=Tournament.objects.all(),
                                        read_only=False)
    participants = PrimaryKeyRelatedField(many=True,
                                          queryset=User.objects.all(),
                                          read_only=False)
    id = IntegerField(read_only=True, source="pk")

    class Meta:
        model = Battle
        fields = ["name", "participants", "tournament", "id"]
Ejemplo n.º 31
0
class BilletSerializer(serializers.ModelSerializer):
    product = PrimaryKeyRelatedField(many=False,
                                     queryset=Product.objects.all())
    options = PrimaryKeyRelatedField(many=True, read_only=True, required=False)
    participants = ParticipantSerializer(many=True, required=False)
    billet_options = BilletOptionSerializer(many=True, required=False)

    class Meta:
        model = models.Billet
        fields = ('id', 'product', 'options', 'billet_options', 'participants')
        depth = 2
Ejemplo n.º 32
0
 def to_internal_value(self, data):
     """Resolve the version only by `id`."""
     # Version queryset is unfiltered, the version is checked more
     # thoroughly in `ReviewSerializer.validate()` method.
     field = PrimaryKeyRelatedField(queryset=Version.unfiltered)
     return field.to_internal_value(data)