Django Rest Framework different serializers for on model












0














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:




  • For first url user’data have to has both fileds (serial_num and
    count) For second url users’data have to has only one field (count).

  • In second case serial_num will be generated in Serializers class.


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).










share|improve this question






















  • I don't see a problem with using multiple serializers for 1 model - you only need separate views for each serializers for different behavior.
    – Chiefir
    2 days ago










  • But what about validate? Both os serializers have to validate field "count" which depends on another model.
    – Mike
    2 days ago










  • yep, you write different validations for each serializer. Of course, you can make it as a separate function and just call it inside serializers, to by DRY.
    – Chiefir
    2 days ago










  • Then you can write a separate class (aka a Mixin) that encapsulates this validation and then apply this mixin (inherit from this class) to both serializers
    – ivissani
    2 days ago










  • What is better way to validate models object? In Model's class or in Serializer class?
    – Mike
    2 days ago
















0














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:




  • For first url user’data have to has both fileds (serial_num and
    count) For second url users’data have to has only one field (count).

  • In second case serial_num will be generated in Serializers class.


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).










share|improve this question






















  • I don't see a problem with using multiple serializers for 1 model - you only need separate views for each serializers for different behavior.
    – Chiefir
    2 days ago










  • But what about validate? Both os serializers have to validate field "count" which depends on another model.
    – Mike
    2 days ago










  • yep, you write different validations for each serializer. Of course, you can make it as a separate function and just call it inside serializers, to by DRY.
    – Chiefir
    2 days ago










  • Then you can write a separate class (aka a Mixin) that encapsulates this validation and then apply this mixin (inherit from this class) to both serializers
    – ivissani
    2 days ago










  • What is better way to validate models object? In Model's class or in Serializer class?
    – Mike
    2 days ago














0












0








0







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:




  • For first url user’data have to has both fileds (serial_num and
    count) For second url users’data have to has only one field (count).

  • In second case serial_num will be generated in Serializers class.


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).










share|improve this question













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:




  • For first url user’data have to has both fileds (serial_num and
    count) For second url users’data have to has only one field (count).

  • In second case serial_num will be generated in Serializers class.


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).







django django-rest-framework






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 2 days ago









Mike

163112




163112












  • I don't see a problem with using multiple serializers for 1 model - you only need separate views for each serializers for different behavior.
    – Chiefir
    2 days ago










  • But what about validate? Both os serializers have to validate field "count" which depends on another model.
    – Mike
    2 days ago










  • yep, you write different validations for each serializer. Of course, you can make it as a separate function and just call it inside serializers, to by DRY.
    – Chiefir
    2 days ago










  • Then you can write a separate class (aka a Mixin) that encapsulates this validation and then apply this mixin (inherit from this class) to both serializers
    – ivissani
    2 days ago










  • What is better way to validate models object? In Model's class or in Serializer class?
    – Mike
    2 days ago


















  • I don't see a problem with using multiple serializers for 1 model - you only need separate views for each serializers for different behavior.
    – Chiefir
    2 days ago










  • But what about validate? Both os serializers have to validate field "count" which depends on another model.
    – Mike
    2 days ago










  • yep, you write different validations for each serializer. Of course, you can make it as a separate function and just call it inside serializers, to by DRY.
    – Chiefir
    2 days ago










  • Then you can write a separate class (aka a Mixin) that encapsulates this validation and then apply this mixin (inherit from this class) to both serializers
    – ivissani
    2 days ago










  • What is better way to validate models object? In Model's class or in Serializer class?
    – Mike
    2 days ago
















I don't see a problem with using multiple serializers for 1 model - you only need separate views for each serializers for different behavior.
– Chiefir
2 days ago




I don't see a problem with using multiple serializers for 1 model - you only need separate views for each serializers for different behavior.
– Chiefir
2 days ago












But what about validate? Both os serializers have to validate field "count" which depends on another model.
– Mike
2 days ago




But what about validate? Both os serializers have to validate field "count" which depends on another model.
– Mike
2 days ago












yep, you write different validations for each serializer. Of course, you can make it as a separate function and just call it inside serializers, to by DRY.
– Chiefir
2 days ago




yep, you write different validations for each serializer. Of course, you can make it as a separate function and just call it inside serializers, to by DRY.
– Chiefir
2 days ago












Then you can write a separate class (aka a Mixin) that encapsulates this validation and then apply this mixin (inherit from this class) to both serializers
– ivissani
2 days ago




Then you can write a separate class (aka a Mixin) that encapsulates this validation and then apply this mixin (inherit from this class) to both serializers
– ivissani
2 days ago












What is better way to validate models object? In Model's class or in Serializer class?
– Mike
2 days ago




What is better way to validate models object? In Model's class or in Serializer class?
– Mike
2 days ago












2 Answers
2






active

oldest

votes


















0














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






share|improve this answer








New contributor




Ivan Cvetković is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.


























    0















    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





    share|improve this answer























    • For viewset actions like list, create, update, etc you must override get_serializer_class() method and return the correct serializer class based on the self.action attribute. Check this
      – Lucas Weyne
      2 days ago











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53945491%2fdjango-rest-framework-different-serializers-for-on-model%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














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






    share|improve this answer








    New contributor




    Ivan Cvetković is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.























      0














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






      share|improve this answer








      New contributor




      Ivan Cvetković is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





















        0












        0








        0






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






        share|improve this answer








        New contributor




        Ivan Cvetković is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









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







        share|improve this answer








        New contributor




        Ivan Cvetković is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        share|improve this answer



        share|improve this answer






        New contributor




        Ivan Cvetković is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        answered 2 days ago









        Ivan Cvetković

        91




        91




        New contributor




        Ivan Cvetković is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.





        New contributor





        Ivan Cvetković is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






        Ivan Cvetković is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.

























            0















            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





            share|improve this answer























            • For viewset actions like list, create, update, etc you must override get_serializer_class() method and return the correct serializer class based on the self.action attribute. Check this
              – Lucas Weyne
              2 days ago
















            0















            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





            share|improve this answer























            • For viewset actions like list, create, update, etc you must override get_serializer_class() method and return the correct serializer class based on the self.action attribute. Check this
              – Lucas Weyne
              2 days ago














            0












            0








            0







            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





            share|improve this answer















            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






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 2 days ago









            Lucas Weyne

            926




            926










            answered 2 days ago









            Reza Torkaman Ahmadi

            596115




            596115












            • For viewset actions like list, create, update, etc you must override get_serializer_class() method and return the correct serializer class based on the self.action attribute. Check this
              – Lucas Weyne
              2 days ago


















            • For viewset actions like list, create, update, etc you must override get_serializer_class() method and return the correct serializer class based on the self.action attribute. Check this
              – Lucas Weyne
              2 days ago
















            For viewset actions like list, create, update, etc you must override get_serializer_class() method and return the correct serializer class based on the self.action attribute. Check this
            – Lucas Weyne
            2 days ago




            For viewset actions like list, create, update, etc you must override get_serializer_class() method and return the correct serializer class based on the self.action attribute. Check this
            – Lucas Weyne
            2 days ago


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53945491%2fdjango-rest-framework-different-serializers-for-on-model%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Mossoró

            Error while reading .h5 file using the rhdf5 package in R

            Pushsharp Apns notification error: 'InvalidToken'