Django: filter() or get()










0















Is the way I write discount_code.first().is_active() the right way, or is it preferable to work with .get as (discount) code is a code unique field per event? Different events can have the code.



def clean_code(self):
input_code = self.cleaned_data['code']

# Check if discount code exists
discount_code = self.event.discounts.filter(code=input_code)
discount_code_exists = discount_code.exists()
if not discount_code_exists:
raise forms.ValidationError(_("The discount code couldn't be found."),
code='code_exists')
else:
if not discount_code.first().is_active():
raise forms.ValidationError(_("This discount code is not available
anymore."),
code='code_not_active')
return input_code









share|improve this question




























    0















    Is the way I write discount_code.first().is_active() the right way, or is it preferable to work with .get as (discount) code is a code unique field per event? Different events can have the code.



    def clean_code(self):
    input_code = self.cleaned_data['code']

    # Check if discount code exists
    discount_code = self.event.discounts.filter(code=input_code)
    discount_code_exists = discount_code.exists()
    if not discount_code_exists:
    raise forms.ValidationError(_("The discount code couldn't be found."),
    code='code_exists')
    else:
    if not discount_code.first().is_active():
    raise forms.ValidationError(_("This discount code is not available
    anymore."),
    code='code_not_active')
    return input_code









    share|improve this question


























      0












      0








      0








      Is the way I write discount_code.first().is_active() the right way, or is it preferable to work with .get as (discount) code is a code unique field per event? Different events can have the code.



      def clean_code(self):
      input_code = self.cleaned_data['code']

      # Check if discount code exists
      discount_code = self.event.discounts.filter(code=input_code)
      discount_code_exists = discount_code.exists()
      if not discount_code_exists:
      raise forms.ValidationError(_("The discount code couldn't be found."),
      code='code_exists')
      else:
      if not discount_code.first().is_active():
      raise forms.ValidationError(_("This discount code is not available
      anymore."),
      code='code_not_active')
      return input_code









      share|improve this question
















      Is the way I write discount_code.first().is_active() the right way, or is it preferable to work with .get as (discount) code is a code unique field per event? Different events can have the code.



      def clean_code(self):
      input_code = self.cleaned_data['code']

      # Check if discount code exists
      discount_code = self.event.discounts.filter(code=input_code)
      discount_code_exists = discount_code.exists()
      if not discount_code_exists:
      raise forms.ValidationError(_("The discount code couldn't be found."),
      code='code_exists')
      else:
      if not discount_code.first().is_active():
      raise forms.ValidationError(_("This discount code is not available
      anymore."),
      code='code_not_active')
      return input_code






      python django






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 14 '18 at 16:36









      Joel

      1,5686719




      1,5686719










      asked Nov 14 '18 at 16:08









      Joey CoderJoey Coder

      3069




      3069






















          2 Answers
          2






          active

          oldest

          votes


















          2














          You can save a query here. The return value of .first() on the queryset has all the info you need for your validation:



          def clean_code(self):
          input_code = self.cleaned_data['code']

          # this is None if it doesn't exist
          discount_code = self.event.discounts.filter(code=input_code).first()

          if not discount_code:
          raise forms.ValidationError(_("The discount code couldn't be found."),
          code='code_exists')
          if not discount_code.is_active():
          raise forms.ValidationError(_("This discount code is not available anymore."),
          code='code_not_active')
          return input_code


          Using exists() is only beneficial if you do not need to process the queryset any further (which you do in the is_active check). And even then, you need large amounts of data to see real performance gains.






          share|improve this answer

























          • As the statement says, "Explicit is better than implicit". To me, seeing filter means "it can return multiple values", and get means "it should return one value". So I find strange doing filter().first() instead of get.

            – mistiru
            Nov 14 '18 at 17:05











          • @mistiru I don't disagree, given the uniqueness of code. Your solution is principled and perfectly valid. I would, however, consider my approach a bit more readable and tidy as all invalid cases are handled and detected in the same way (if).

            – schwobaseggl
            Nov 14 '18 at 17:22



















          1














          I would have written the code this way:



          def clean_code(self):
          input_code = self.cleaned_data['code']

          try:
          discount_code = self.event.discounts.get(code=input_code)
          except Discount.DoesNotExist: # suppose your model is named Discount
          raise forms.ValidationError(_("The discount code couldn't be found."),
          code='code_exists')

          if not discount_code.is_active():
          raise forms.ValidationError(_("This discount code is not available anymore."),
          code='code_not_active')

          return input_code





          share|improve this answer






















            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%2f53304392%2fdjango-filter-or-get%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









            2














            You can save a query here. The return value of .first() on the queryset has all the info you need for your validation:



            def clean_code(self):
            input_code = self.cleaned_data['code']

            # this is None if it doesn't exist
            discount_code = self.event.discounts.filter(code=input_code).first()

            if not discount_code:
            raise forms.ValidationError(_("The discount code couldn't be found."),
            code='code_exists')
            if not discount_code.is_active():
            raise forms.ValidationError(_("This discount code is not available anymore."),
            code='code_not_active')
            return input_code


            Using exists() is only beneficial if you do not need to process the queryset any further (which you do in the is_active check). And even then, you need large amounts of data to see real performance gains.






            share|improve this answer

























            • As the statement says, "Explicit is better than implicit". To me, seeing filter means "it can return multiple values", and get means "it should return one value". So I find strange doing filter().first() instead of get.

              – mistiru
              Nov 14 '18 at 17:05











            • @mistiru I don't disagree, given the uniqueness of code. Your solution is principled and perfectly valid. I would, however, consider my approach a bit more readable and tidy as all invalid cases are handled and detected in the same way (if).

              – schwobaseggl
              Nov 14 '18 at 17:22
















            2














            You can save a query here. The return value of .first() on the queryset has all the info you need for your validation:



            def clean_code(self):
            input_code = self.cleaned_data['code']

            # this is None if it doesn't exist
            discount_code = self.event.discounts.filter(code=input_code).first()

            if not discount_code:
            raise forms.ValidationError(_("The discount code couldn't be found."),
            code='code_exists')
            if not discount_code.is_active():
            raise forms.ValidationError(_("This discount code is not available anymore."),
            code='code_not_active')
            return input_code


            Using exists() is only beneficial if you do not need to process the queryset any further (which you do in the is_active check). And even then, you need large amounts of data to see real performance gains.






            share|improve this answer

























            • As the statement says, "Explicit is better than implicit". To me, seeing filter means "it can return multiple values", and get means "it should return one value". So I find strange doing filter().first() instead of get.

              – mistiru
              Nov 14 '18 at 17:05











            • @mistiru I don't disagree, given the uniqueness of code. Your solution is principled and perfectly valid. I would, however, consider my approach a bit more readable and tidy as all invalid cases are handled and detected in the same way (if).

              – schwobaseggl
              Nov 14 '18 at 17:22














            2












            2








            2







            You can save a query here. The return value of .first() on the queryset has all the info you need for your validation:



            def clean_code(self):
            input_code = self.cleaned_data['code']

            # this is None if it doesn't exist
            discount_code = self.event.discounts.filter(code=input_code).first()

            if not discount_code:
            raise forms.ValidationError(_("The discount code couldn't be found."),
            code='code_exists')
            if not discount_code.is_active():
            raise forms.ValidationError(_("This discount code is not available anymore."),
            code='code_not_active')
            return input_code


            Using exists() is only beneficial if you do not need to process the queryset any further (which you do in the is_active check). And even then, you need large amounts of data to see real performance gains.






            share|improve this answer















            You can save a query here. The return value of .first() on the queryset has all the info you need for your validation:



            def clean_code(self):
            input_code = self.cleaned_data['code']

            # this is None if it doesn't exist
            discount_code = self.event.discounts.filter(code=input_code).first()

            if not discount_code:
            raise forms.ValidationError(_("The discount code couldn't be found."),
            code='code_exists')
            if not discount_code.is_active():
            raise forms.ValidationError(_("This discount code is not available anymore."),
            code='code_not_active')
            return input_code


            Using exists() is only beneficial if you do not need to process the queryset any further (which you do in the is_active check). And even then, you need large amounts of data to see real performance gains.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 14 '18 at 16:49

























            answered Nov 14 '18 at 16:43









            schwobasegglschwobaseggl

            37.4k32442




            37.4k32442












            • As the statement says, "Explicit is better than implicit". To me, seeing filter means "it can return multiple values", and get means "it should return one value". So I find strange doing filter().first() instead of get.

              – mistiru
              Nov 14 '18 at 17:05











            • @mistiru I don't disagree, given the uniqueness of code. Your solution is principled and perfectly valid. I would, however, consider my approach a bit more readable and tidy as all invalid cases are handled and detected in the same way (if).

              – schwobaseggl
              Nov 14 '18 at 17:22


















            • As the statement says, "Explicit is better than implicit". To me, seeing filter means "it can return multiple values", and get means "it should return one value". So I find strange doing filter().first() instead of get.

              – mistiru
              Nov 14 '18 at 17:05











            • @mistiru I don't disagree, given the uniqueness of code. Your solution is principled and perfectly valid. I would, however, consider my approach a bit more readable and tidy as all invalid cases are handled and detected in the same way (if).

              – schwobaseggl
              Nov 14 '18 at 17:22

















            As the statement says, "Explicit is better than implicit". To me, seeing filter means "it can return multiple values", and get means "it should return one value". So I find strange doing filter().first() instead of get.

            – mistiru
            Nov 14 '18 at 17:05





            As the statement says, "Explicit is better than implicit". To me, seeing filter means "it can return multiple values", and get means "it should return one value". So I find strange doing filter().first() instead of get.

            – mistiru
            Nov 14 '18 at 17:05













            @mistiru I don't disagree, given the uniqueness of code. Your solution is principled and perfectly valid. I would, however, consider my approach a bit more readable and tidy as all invalid cases are handled and detected in the same way (if).

            – schwobaseggl
            Nov 14 '18 at 17:22






            @mistiru I don't disagree, given the uniqueness of code. Your solution is principled and perfectly valid. I would, however, consider my approach a bit more readable and tidy as all invalid cases are handled and detected in the same way (if).

            – schwobaseggl
            Nov 14 '18 at 17:22














            1














            I would have written the code this way:



            def clean_code(self):
            input_code = self.cleaned_data['code']

            try:
            discount_code = self.event.discounts.get(code=input_code)
            except Discount.DoesNotExist: # suppose your model is named Discount
            raise forms.ValidationError(_("The discount code couldn't be found."),
            code='code_exists')

            if not discount_code.is_active():
            raise forms.ValidationError(_("This discount code is not available anymore."),
            code='code_not_active')

            return input_code





            share|improve this answer



























              1














              I would have written the code this way:



              def clean_code(self):
              input_code = self.cleaned_data['code']

              try:
              discount_code = self.event.discounts.get(code=input_code)
              except Discount.DoesNotExist: # suppose your model is named Discount
              raise forms.ValidationError(_("The discount code couldn't be found."),
              code='code_exists')

              if not discount_code.is_active():
              raise forms.ValidationError(_("This discount code is not available anymore."),
              code='code_not_active')

              return input_code





              share|improve this answer

























                1












                1








                1







                I would have written the code this way:



                def clean_code(self):
                input_code = self.cleaned_data['code']

                try:
                discount_code = self.event.discounts.get(code=input_code)
                except Discount.DoesNotExist: # suppose your model is named Discount
                raise forms.ValidationError(_("The discount code couldn't be found."),
                code='code_exists')

                if not discount_code.is_active():
                raise forms.ValidationError(_("This discount code is not available anymore."),
                code='code_not_active')

                return input_code





                share|improve this answer













                I would have written the code this way:



                def clean_code(self):
                input_code = self.cleaned_data['code']

                try:
                discount_code = self.event.discounts.get(code=input_code)
                except Discount.DoesNotExist: # suppose your model is named Discount
                raise forms.ValidationError(_("The discount code couldn't be found."),
                code='code_exists')

                if not discount_code.is_active():
                raise forms.ValidationError(_("This discount code is not available anymore."),
                code='code_not_active')

                return input_code






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 14 '18 at 16:58









                mistirumistiru

                440113




                440113



























                    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.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53304392%2fdjango-filter-or-get%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

                    Use pre created SQLite database for Android project in kotlin

                    Darth Vader #20

                    Ondo