Mike
Mike

Reputation: 878

Django Rest Framework different serializers for on model

I have Model, like:

 def SomeModel(models.Model):
     serial_num = models.IntegerField(unique=True)
     count = models.IntegerField()

And have to create 2 url which will work with this model. But, there are have to be 2 different serializers. For example:

Is this good practice to make 2 different serializers for one model?

And also question, what about validation?

Field “count” is depends on another model. I thought put validate into serializer class. But I don’t want to have 2 the same blocks of validation code in 2 different serializers classes (for both urls).

Upvotes: 0

Views: 2624

Answers (3)

Mike
Mike

Reputation: 878

I've found approach which may be more usefull. Use services for business logic. Example can read here: https://github.com/HackSoftware/django-styleguide#examples

Upvotes: -1

Reza Torkaman Ahmadi
Reza Torkaman Ahmadi

Reputation: 3058

Create two serializers and assign each of your views to that specific serializer.

for example, imagine you have two path like path1 and path2:

class MyModelViewSet(ModelViewSet):
    serializer_class = Serializer1
    queryset = YourModel.objects.all()

    @action(methods=['post'], detail=False, url_path='path1', serializer_class=Serializer1)
    def path1_view(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        .....

    @action(methods=['post'], detail=False, url_path='path2', serializer_class=Serializer2)
    def path2_view(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        .....

and for serializers:

class Serializer1(ModelSerializer):
    class Meta:
        model = SomeModel
        fields = ('serial_num', 'count',)

class Serializer2(ModelSerializer):
    class Meta:
        model = SomeModel
        fields = ('count',)

    def validate(self, attrs):
        # Update attrs with serial_num here
        return attrs

Upvotes: 1

Ivan Cvetković
Ivan Cvetković

Reputation: 174

You should use two serializers and use inheritance for common validation logic.

Upvotes: 0

Related Questions