Chau Loi
Chau Loi

Reputation: 1225

Django - Can I create a Serializer without connecting to a model?

From the book, I do this to create a Serializers

class Serielizer_RecalculateDeliveryPromise(serializers.ModelSerializer):
    service_type = serializers.CharField(max_length = 10, write_only= True, required= True )
    package_type = serializers.CharField(max_length = 68, write_only= True,  required= True )
    origin_handover_point = serializers.CharField(max_length = 68, write_only= True, required= True  )
    destination_handover_point = serializers.CharField(max_length = 68, write_only= True,required= True  )
    class Meta:
        model = Input_RecalculateDeliveryPromise
        fields = ['service_type', 'package_type', 'origin_handover_point', 'destination_handover_point']


class Input_RecalculateDeliveryPromise(models.Model):
    service_type = models.CharField(max_length = 10, db_index = True)
    package_type = models.CharField(max_length = 68, db_index = True)
    origin_handover_point = models.CharField(max_length = 68, db_index = True)
    destination_handover_point = models.CharField(max_length = 68, db_index = True)
    REQUIRED_FIELDS = ['service_type', 'package_type', 'origin_hp','destination_hp']

My personal purpose of Serializer is simply to check the input only.

Therefore, I wonder if there is anyway that I could create a Serializer only without connecting to any model since it lengthen my code a lot.

Upvotes: 1

Views: 61

Answers (1)

josephthomaa
josephthomaa

Reputation: 158

You can use serializers.Serializer instead of serializers.ModelSerializer

class Serielizer_RecalculateDeliveryPromise(serializers.Serializer):
    service_type = serializers.CharField(max_length = 10, write_only= True, required= True )
    package_type = serializers.CharField(max_length = 68, write_only= True,  required= True )
    origin_handover_point = serializers.CharField(max_length = 68, write_only= True, required= True  )
    destination_handover_point = serializers.CharField(max_length = 68, write_only= True,required= True  )

Upvotes: 1

Related Questions