Django Rest API VIEWSET custom validation on post request











up vote
0
down vote

favorite












I'm new to django rest framework.



Here is model.py



PRICE_CHOICES = (
('high','High'),
('medium', 'Medium'),
('low','Low'),
)
class Book(models.Model):
price = models.CharField(max_length=255)
status = models.CharField(max_length=255,choices=PRICE_CHOICES)


My api views.py:



class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer


and serializer.py:



class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('id', 'price', 'status')


want to override price field.










share|improve this question
























  • what do you want to do with price field?
    – Rohit Chopra
    Oct 29 at 10:40










  • Just want to return if price is high
    – nikolas
    Oct 29 at 10:44










  • ok you want to show price if it is high else remove this field?
    – Rohit Chopra
    Oct 29 at 10:58










  • If price is high I want to alert him price is high
    – nikolas
    Oct 29 at 10:59















up vote
0
down vote

favorite












I'm new to django rest framework.



Here is model.py



PRICE_CHOICES = (
('high','High'),
('medium', 'Medium'),
('low','Low'),
)
class Book(models.Model):
price = models.CharField(max_length=255)
status = models.CharField(max_length=255,choices=PRICE_CHOICES)


My api views.py:



class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer


and serializer.py:



class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('id', 'price', 'status')


want to override price field.










share|improve this question
























  • what do you want to do with price field?
    – Rohit Chopra
    Oct 29 at 10:40










  • Just want to return if price is high
    – nikolas
    Oct 29 at 10:44










  • ok you want to show price if it is high else remove this field?
    – Rohit Chopra
    Oct 29 at 10:58










  • If price is high I want to alert him price is high
    – nikolas
    Oct 29 at 10:59













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I'm new to django rest framework.



Here is model.py



PRICE_CHOICES = (
('high','High'),
('medium', 'Medium'),
('low','Low'),
)
class Book(models.Model):
price = models.CharField(max_length=255)
status = models.CharField(max_length=255,choices=PRICE_CHOICES)


My api views.py:



class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer


and serializer.py:



class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('id', 'price', 'status')


want to override price field.










share|improve this question















I'm new to django rest framework.



Here is model.py



PRICE_CHOICES = (
('high','High'),
('medium', 'Medium'),
('low','Low'),
)
class Book(models.Model):
price = models.CharField(max_length=255)
status = models.CharField(max_length=255,choices=PRICE_CHOICES)


My api views.py:



class BookViewSet(viewsets.ModelViewSet):
queryset = Book.objects.all()
serializer_class = BookSerializer


and serializer.py:



class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('id', 'price', 'status')


want to override price field.







django django-rest-framework






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 29 at 12:41

























asked Oct 29 at 10:34









nikolas

5901927




5901927












  • what do you want to do with price field?
    – Rohit Chopra
    Oct 29 at 10:40










  • Just want to return if price is high
    – nikolas
    Oct 29 at 10:44










  • ok you want to show price if it is high else remove this field?
    – Rohit Chopra
    Oct 29 at 10:58










  • If price is high I want to alert him price is high
    – nikolas
    Oct 29 at 10:59


















  • what do you want to do with price field?
    – Rohit Chopra
    Oct 29 at 10:40










  • Just want to return if price is high
    – nikolas
    Oct 29 at 10:44










  • ok you want to show price if it is high else remove this field?
    – Rohit Chopra
    Oct 29 at 10:58










  • If price is high I want to alert him price is high
    – nikolas
    Oct 29 at 10:59
















what do you want to do with price field?
– Rohit Chopra
Oct 29 at 10:40




what do you want to do with price field?
– Rohit Chopra
Oct 29 at 10:40












Just want to return if price is high
– nikolas
Oct 29 at 10:44




Just want to return if price is high
– nikolas
Oct 29 at 10:44












ok you want to show price if it is high else remove this field?
– Rohit Chopra
Oct 29 at 10:58




ok you want to show price if it is high else remove this field?
– Rohit Chopra
Oct 29 at 10:58












If price is high I want to alert him price is high
– nikolas
Oct 29 at 10:59




If price is high I want to alert him price is high
– nikolas
Oct 29 at 10:59












2 Answers
2






active

oldest

votes

















up vote
1
down vote



accepted










U can use validation in many ways. Below is a sample



    class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('id', 'price', 'status')

def create(self, validated_data):
# logic for creating object
# you can extract data from validated_data['name'] and then put your logic
return validated_data

def update(self, instance, validated_data):
# logic for updating object
return instance





share|improve this answer






























    up vote
    1
    down vote













    You can throw an error when price exceeds a limit like this.



     class BookSerializer(serializers.ModelSerializer):
    class Meta:
    model = Book
    fields = ('id', 'price', 'status')

    def validate_price(self, data):
    if data > threshold:
    raise ValidationError(message='...')
    return data


    If you want to alert a user and based on his response you want to make a decision then you need other logic. You need to introduce a new check variable/param in post input.



    To set one book for user per day override validate method in serializer



    class BookSerializer(serializers.ModelSerializer):
    class Meta:
    model = Book
    fields = ('id', 'price', 'status')

    def validate_price(self, data):
    if data > threshold:
    raise ValidationError(message='...')
    return data
    def validate(self, data):
    # your logic, et user detail and date and check it with db. if found raise exception as shown above.





    share|improve this answer























    • Thanks. If I want user can only one book in a single day How to implement this
      – nikolas
      Oct 29 at 11:45












    • The model is missing and I have only limited info. But I updated answer and it may help.
      – a_k_v
      Oct 29 at 11:56










    • check the updated ques. I've added model
      – nikolas
      Oct 29 at 12:41










    • @a_k_v In your answer, if the price is higher than the threshold, the data will not be saved in DB. It needs to be clear what is the requirement here i.e. if we don't want to save higher price or do we want to save a higher price but with some kind of notification to the user. If the latter is the case, we can use signals with the post_save receiver.
      – amulya349
      Oct 29 at 12:58










    • @a_k_v thanks bro. Its works
      – nikolas
      Oct 29 at 13:29











    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%2f53043624%2fdjango-rest-api-viewset-custom-validation-on-post-request%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








    up vote
    1
    down vote



    accepted










    U can use validation in many ways. Below is a sample



        class BookSerializer(serializers.ModelSerializer):
    class Meta:
    model = Book
    fields = ('id', 'price', 'status')

    def create(self, validated_data):
    # logic for creating object
    # you can extract data from validated_data['name'] and then put your logic
    return validated_data

    def update(self, instance, validated_data):
    # logic for updating object
    return instance





    share|improve this answer



























      up vote
      1
      down vote



      accepted










      U can use validation in many ways. Below is a sample



          class BookSerializer(serializers.ModelSerializer):
      class Meta:
      model = Book
      fields = ('id', 'price', 'status')

      def create(self, validated_data):
      # logic for creating object
      # you can extract data from validated_data['name'] and then put your logic
      return validated_data

      def update(self, instance, validated_data):
      # logic for updating object
      return instance





      share|improve this answer

























        up vote
        1
        down vote



        accepted







        up vote
        1
        down vote



        accepted






        U can use validation in many ways. Below is a sample



            class BookSerializer(serializers.ModelSerializer):
        class Meta:
        model = Book
        fields = ('id', 'price', 'status')

        def create(self, validated_data):
        # logic for creating object
        # you can extract data from validated_data['name'] and then put your logic
        return validated_data

        def update(self, instance, validated_data):
        # logic for updating object
        return instance





        share|improve this answer














        U can use validation in many ways. Below is a sample



            class BookSerializer(serializers.ModelSerializer):
        class Meta:
        model = Book
        fields = ('id', 'price', 'status')

        def create(self, validated_data):
        # logic for creating object
        # you can extract data from validated_data['name'] and then put your logic
        return validated_data

        def update(self, instance, validated_data):
        # logic for updating object
        return instance






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 10 at 13:07

























        answered Nov 10 at 12:50









        Hamim Al Mahdi Russell

        641310




        641310
























            up vote
            1
            down vote













            You can throw an error when price exceeds a limit like this.



             class BookSerializer(serializers.ModelSerializer):
            class Meta:
            model = Book
            fields = ('id', 'price', 'status')

            def validate_price(self, data):
            if data > threshold:
            raise ValidationError(message='...')
            return data


            If you want to alert a user and based on his response you want to make a decision then you need other logic. You need to introduce a new check variable/param in post input.



            To set one book for user per day override validate method in serializer



            class BookSerializer(serializers.ModelSerializer):
            class Meta:
            model = Book
            fields = ('id', 'price', 'status')

            def validate_price(self, data):
            if data > threshold:
            raise ValidationError(message='...')
            return data
            def validate(self, data):
            # your logic, et user detail and date and check it with db. if found raise exception as shown above.





            share|improve this answer























            • Thanks. If I want user can only one book in a single day How to implement this
              – nikolas
              Oct 29 at 11:45












            • The model is missing and I have only limited info. But I updated answer and it may help.
              – a_k_v
              Oct 29 at 11:56










            • check the updated ques. I've added model
              – nikolas
              Oct 29 at 12:41










            • @a_k_v In your answer, if the price is higher than the threshold, the data will not be saved in DB. It needs to be clear what is the requirement here i.e. if we don't want to save higher price or do we want to save a higher price but with some kind of notification to the user. If the latter is the case, we can use signals with the post_save receiver.
              – amulya349
              Oct 29 at 12:58










            • @a_k_v thanks bro. Its works
              – nikolas
              Oct 29 at 13:29















            up vote
            1
            down vote













            You can throw an error when price exceeds a limit like this.



             class BookSerializer(serializers.ModelSerializer):
            class Meta:
            model = Book
            fields = ('id', 'price', 'status')

            def validate_price(self, data):
            if data > threshold:
            raise ValidationError(message='...')
            return data


            If you want to alert a user and based on his response you want to make a decision then you need other logic. You need to introduce a new check variable/param in post input.



            To set one book for user per day override validate method in serializer



            class BookSerializer(serializers.ModelSerializer):
            class Meta:
            model = Book
            fields = ('id', 'price', 'status')

            def validate_price(self, data):
            if data > threshold:
            raise ValidationError(message='...')
            return data
            def validate(self, data):
            # your logic, et user detail and date and check it with db. if found raise exception as shown above.





            share|improve this answer























            • Thanks. If I want user can only one book in a single day How to implement this
              – nikolas
              Oct 29 at 11:45












            • The model is missing and I have only limited info. But I updated answer and it may help.
              – a_k_v
              Oct 29 at 11:56










            • check the updated ques. I've added model
              – nikolas
              Oct 29 at 12:41










            • @a_k_v In your answer, if the price is higher than the threshold, the data will not be saved in DB. It needs to be clear what is the requirement here i.e. if we don't want to save higher price or do we want to save a higher price but with some kind of notification to the user. If the latter is the case, we can use signals with the post_save receiver.
              – amulya349
              Oct 29 at 12:58










            • @a_k_v thanks bro. Its works
              – nikolas
              Oct 29 at 13:29













            up vote
            1
            down vote










            up vote
            1
            down vote









            You can throw an error when price exceeds a limit like this.



             class BookSerializer(serializers.ModelSerializer):
            class Meta:
            model = Book
            fields = ('id', 'price', 'status')

            def validate_price(self, data):
            if data > threshold:
            raise ValidationError(message='...')
            return data


            If you want to alert a user and based on his response you want to make a decision then you need other logic. You need to introduce a new check variable/param in post input.



            To set one book for user per day override validate method in serializer



            class BookSerializer(serializers.ModelSerializer):
            class Meta:
            model = Book
            fields = ('id', 'price', 'status')

            def validate_price(self, data):
            if data > threshold:
            raise ValidationError(message='...')
            return data
            def validate(self, data):
            # your logic, et user detail and date and check it with db. if found raise exception as shown above.





            share|improve this answer














            You can throw an error when price exceeds a limit like this.



             class BookSerializer(serializers.ModelSerializer):
            class Meta:
            model = Book
            fields = ('id', 'price', 'status')

            def validate_price(self, data):
            if data > threshold:
            raise ValidationError(message='...')
            return data


            If you want to alert a user and based on his response you want to make a decision then you need other logic. You need to introduce a new check variable/param in post input.



            To set one book for user per day override validate method in serializer



            class BookSerializer(serializers.ModelSerializer):
            class Meta:
            model = Book
            fields = ('id', 'price', 'status')

            def validate_price(self, data):
            if data > threshold:
            raise ValidationError(message='...')
            return data
            def validate(self, data):
            # your logic, et user detail and date and check it with db. if found raise exception as shown above.






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Oct 29 at 11:54

























            answered Oct 29 at 11:10









            a_k_v

            725112




            725112












            • Thanks. If I want user can only one book in a single day How to implement this
              – nikolas
              Oct 29 at 11:45












            • The model is missing and I have only limited info. But I updated answer and it may help.
              – a_k_v
              Oct 29 at 11:56










            • check the updated ques. I've added model
              – nikolas
              Oct 29 at 12:41










            • @a_k_v In your answer, if the price is higher than the threshold, the data will not be saved in DB. It needs to be clear what is the requirement here i.e. if we don't want to save higher price or do we want to save a higher price but with some kind of notification to the user. If the latter is the case, we can use signals with the post_save receiver.
              – amulya349
              Oct 29 at 12:58










            • @a_k_v thanks bro. Its works
              – nikolas
              Oct 29 at 13:29


















            • Thanks. If I want user can only one book in a single day How to implement this
              – nikolas
              Oct 29 at 11:45












            • The model is missing and I have only limited info. But I updated answer and it may help.
              – a_k_v
              Oct 29 at 11:56










            • check the updated ques. I've added model
              – nikolas
              Oct 29 at 12:41










            • @a_k_v In your answer, if the price is higher than the threshold, the data will not be saved in DB. It needs to be clear what is the requirement here i.e. if we don't want to save higher price or do we want to save a higher price but with some kind of notification to the user. If the latter is the case, we can use signals with the post_save receiver.
              – amulya349
              Oct 29 at 12:58










            • @a_k_v thanks bro. Its works
              – nikolas
              Oct 29 at 13:29
















            Thanks. If I want user can only one book in a single day How to implement this
            – nikolas
            Oct 29 at 11:45






            Thanks. If I want user can only one book in a single day How to implement this
            – nikolas
            Oct 29 at 11:45














            The model is missing and I have only limited info. But I updated answer and it may help.
            – a_k_v
            Oct 29 at 11:56




            The model is missing and I have only limited info. But I updated answer and it may help.
            – a_k_v
            Oct 29 at 11:56












            check the updated ques. I've added model
            – nikolas
            Oct 29 at 12:41




            check the updated ques. I've added model
            – nikolas
            Oct 29 at 12:41












            @a_k_v In your answer, if the price is higher than the threshold, the data will not be saved in DB. It needs to be clear what is the requirement here i.e. if we don't want to save higher price or do we want to save a higher price but with some kind of notification to the user. If the latter is the case, we can use signals with the post_save receiver.
            – amulya349
            Oct 29 at 12:58




            @a_k_v In your answer, if the price is higher than the threshold, the data will not be saved in DB. It needs to be clear what is the requirement here i.e. if we don't want to save higher price or do we want to save a higher price but with some kind of notification to the user. If the latter is the case, we can use signals with the post_save receiver.
            – amulya349
            Oct 29 at 12:58












            @a_k_v thanks bro. Its works
            – nikolas
            Oct 29 at 13:29




            @a_k_v thanks bro. Its works
            – nikolas
            Oct 29 at 13:29


















            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%2f53043624%2fdjango-rest-api-viewset-custom-validation-on-post-request%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







            這個網誌中的熱門文章

            Xamarin.form Move up view when keyboard appear

            Post-Redirect-Get with Spring WebFlux and Thymeleaf

            Anylogic : not able to use stopDelay()