Home > OS >  how to make fields optional? DRF
how to make fields optional? DRF

Time:11-05

I use django-rest-framework and I want the "role" and "function" fields to be optional when creating a statement.

Please, tell me how can I do this?

I tried some tricks, example:

I tried:

function = FunctionsCreateSerializer(write_only=True, allow_null=True)

and

class Meta:
    ...

    optional_fields = [...]

but I got

"function": [
        "This field is required."
    ]

when I try:

function = FunctionsCreateSerializer(write_only=True, required=False)

I get:

KeyError at /api/user/ 'function''

I really don't understand how I could change my serializers

models.py

class Operator(models.Model):
    ...
    role = models.ForeignKey("OperatorRole", related_name="operator", on_delete=models.CASCADE, null=True, blank=True)


class OperatorRole(models.Model):
    function = models.ManyToManyField("FunctionRole", null=True)
    role = models.TextField(
        max_length=2,
        choices=Role.choices,
        default=Role.THERMIST
    )


class FunctionRole(models.Model):
    function = models.TextField(
        max_length=4,
        choices=Function.choices,
        default=Function.TPST,
        blank=True,
        null=True,
    )

serizlizers.py

class UserSerializer(serializers.ModelSerializer):
    ...
    role = RoleSerializer()
    function = FunctionsCreateSerializer(write_only=True)

     class Meta:
        model = models.Operator
        fields = ["id", "username", "password", "email", "is_active", "fio", "position", "phone", "role", "function",
                  "created", "updated"]


class FunctionsSerializer(serializers.ModelSerializer):

    def to_representation(self, instance):
        return instance.function

    class Meta:
        model = models.FunctionRole
        fields = ("function",)


class FunctionsCreateSerializer(serializers.ModelSerializer):
    function = serializers.MultipleChoiceField(choices=models.Function)


    class Meta:
        model = models.FunctionRole
        fields = ("function",)
        validators = []


class RoleSerializer(serializers.ModelSerializer):
    functions = FunctionsSerializer(many=True, read_only=True, source='function', required=False)

    class Meta:
        model = models.OperatorRole
        fields = ("role", "functions",)

views.py

class UserList(generics.ListCreateAPIView):
    queryset = models.Operator.objects.all()
    serializer_class = serializers.UserSerializer
    permission_classes = ADMIN_PERMISSIONS
    filter_backends = DEFAULT_FILTERS
    filter_class = UserFilter
    search_fields = ["user__username", "user__email", "fio", "position",
                     "phone", "role__role", "role__function__function"]

    def create(self, request, *args, **kwargs):
        serializer = serializers.UserSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

CodePudding user response:

The problem is that : You are using UserSerializer in the UserList view. But in that serializer, you have this line : function = FunctionsCreateSerializer(write_only=True). As you guess, it's then required by default. If you want make the function field optional, then :

  1. function = FunctionsCreateSerializer(write_only=True, required=False)

  2. remove the line function = FunctionsCreateSerializer(write_only=True) from the UserSerializer and remove the field function from Meta fields too.

  • Related