Home > Net >  Django Rest Framework creatable fields and updatable fields
Django Rest Framework creatable fields and updatable fields

Time:06-20

Below is my sample model:

class DemoModel(models.Model):
    field_one = models.IntegerField()
    field_two = models.IntegerField(blank=True, null=True)

The Serializer:

class DemoSerializer(serializers.ModelSerializer):
    """
    Here only field_one should be creatable and only field_two should be updatable
    """
    class Meta:
        model = models.DemoModel
        fields = '__all__'

My question is how can I write the view for this serializer and model, so that when using the post method the client can not add data for the field_two field. Client can only add data to field_one. But while updating, the client can update the value of field_two, but can not update the value of field_one field.

Thank you

CodePudding user response:

You could create 2 different forms (with different fields), and in your views.py display a form depending whether or not the model already exists.

CodePudding user response:

You can need to create put method to update value, and post method to create value

from rest_framework.permissions import AllowAny
from rest_framework.views import APIView

class Demo_view(APIView):
    permission_classes = [AllowAny]
    # if field doesnt exist
    def post(self, request): 
        field_from_user=request.data["field_from_user"]
        target_object = DemoModel.objects.get(pk=1)
        #check if field one exist
        if target_object.field_one:
            #if it exists then return error
            return Response({'status':200, 'message':"field already exist"})
        #if it doesnt exist create it
        else:
            #logic with creation of the field
            target_object.field_one = "some value here"
            target_object.save()
            return Response({'status':200, 'message':"field created"})
            
    #if you want to update you need to use put method
    def put(self, request): 
        field_from_user=request.data["field_from_user"]
        target_object = DemoModel.objects.get(pk=1)
        #check if this field exist:
        if target_object.field_two:
            #if it is, so update it
            target_object.field_two = "new value"
            target_object.save()
        #if it doesnt exist then return error or smth
        else:
            return Response({'status':200, 'message':"field doesnt exist"})
  • Related