Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I write two different serializers for requests POST and GET?

Here is MODEL:

class Device (models.Model):
    name = models.CharField(max_length = 30)
    device_id = models.CharField(max_length = 100, unique = True)
    organization = models.ForeignKey(Organization)

Here is SERIALIZER:

class DeviceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Device
        fields = ['id','device_id', 'organization']
    def create(self,validated_data):
        validated_data.__setitem__('name', names.get_full_name())
        return Device.objects.create(**validated_data)

Here is API:

class DeviceAPI(APIView):
    def post(self,request,format=None):
        serializer = DeviceSerializer(data = request.data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data , status = 201)
        return JSONResponse(serializer.errors, status = 400)
    def get(self,request,format=None):
       # --------------------------------- #
       # ---- WHAT to write here ??? ----- #
       # --------------------------------- #
       return JSONResponse(serializer.data, status = 200)   

I want this:

if method.request == POST:
   pass  # get post data and create new device  // it's work 
if method.request == GET:
   pass  # receive data (device_id) and if it's exists then send it's id

can I do it using only one serializer or I should write second (for one method - one serializer )

Thanks ! ! !

like image 448
Anuar Akhmetov Avatar asked Nov 03 '25 19:11

Anuar Akhmetov


1 Answers

The best way to do this is to have just one serializer but make sure it has proper annotations for which fields are read-only and which fields are read-write.

If you are using a simple ModelSerializer, it will look something like this:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = [ 'username', 'first_name', 'last_name', 'email' ]
        read_only_fields = [ 'username' ]

This creates a serializer that outputs the four fields listed in the fields parameter, but only the last three are editable using the serializer.

Then just use a ModelViewSet (or some other ViewSet) and let the REST Framework build all the methods for you instead of writing them all by hand.

In some cases, you would need a different serializer for user creation (as the user needs a way to select a username when they first create an account)... for that you can use the example at Django REST Framework show multiple forms on HTML view.

like image 138
seawolf Avatar answered Nov 05 '25 09:11

seawolf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!