How does Django maintain consistency between its logical constraints, and its database?












2














Lets say I have a model defined as follows:



class Foo(models.Model):
bar = models.CharField(max_length=10)


Using this model, I create a Foo object in my database using the following code:



Foo.objects.create(bar="0123456789")


Should work well enough. However, after creating the object, I reduce the max_length property to 5. So now, technically, the object I created has a consistency error.



How does Django manage a situation like this? I assume they don't raise any errors until that object is saved again. If so, is that the optimal solution for a situation like this, and are there are any other approaches?










share|improve this question



























    2














    Lets say I have a model defined as follows:



    class Foo(models.Model):
    bar = models.CharField(max_length=10)


    Using this model, I create a Foo object in my database using the following code:



    Foo.objects.create(bar="0123456789")


    Should work well enough. However, after creating the object, I reduce the max_length property to 5. So now, technically, the object I created has a consistency error.



    How does Django manage a situation like this? I assume they don't raise any errors until that object is saved again. If so, is that the optimal solution for a situation like this, and are there are any other approaches?










    share|improve this question

























      2












      2








      2


      1





      Lets say I have a model defined as follows:



      class Foo(models.Model):
      bar = models.CharField(max_length=10)


      Using this model, I create a Foo object in my database using the following code:



      Foo.objects.create(bar="0123456789")


      Should work well enough. However, after creating the object, I reduce the max_length property to 5. So now, technically, the object I created has a consistency error.



      How does Django manage a situation like this? I assume they don't raise any errors until that object is saved again. If so, is that the optimal solution for a situation like this, and are there are any other approaches?










      share|improve this question













      Lets say I have a model defined as follows:



      class Foo(models.Model):
      bar = models.CharField(max_length=10)


      Using this model, I create a Foo object in my database using the following code:



      Foo.objects.create(bar="0123456789")


      Should work well enough. However, after creating the object, I reduce the max_length property to 5. So now, technically, the object I created has a consistency error.



      How does Django manage a situation like this? I assume they don't raise any errors until that object is saved again. If so, is that the optimal solution for a situation like this, and are there are any other approaches?







      django database django-database






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 10 at 17:39









      darkhorse

      1,36441845




      1,36441845
























          2 Answers
          2






          active

          oldest

          votes


















          1














          It depends on the specific field property. In the case of max_length, it's used in several validation steps in addition to the database itself.



          The default html widget will insert a maxlength attribute in the <input> form element. And on the server side, Form.clean() will also check the length of any char fields.



          Finally, the database will throw an error (if you have created and applied a new migration after changing the field). But the specific behaviour here depends on the database backend.



          Client side validation is just a usability feature. All data coming from the client must also be validated on the server, since client side validation can be bypassed by an attacker, or be turned off or unavailable in some clients.



          Django's validation is what you use most of the time. It has error handling and http responses built in if you use a framework/app such as django forms, django admin or django rest framework.



          The database validation is fallback when you insert some invalid data even if it's "not supposed to be possible". Errors here could result in a uncaught exception and the entire transaction will be rolled back. It's a very useful safety net when you have bugs in your django application.






          share|improve this answer































            3














            Django won't do anything in the situation you describe. However, if you run makemigrations, it will generate a database migration which modifies the db column to 5 characters; running this will truncate the existing values.






            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%2f53241677%2fhow-does-django-maintain-consistency-between-its-logical-constraints-and-its-da%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









              1














              It depends on the specific field property. In the case of max_length, it's used in several validation steps in addition to the database itself.



              The default html widget will insert a maxlength attribute in the <input> form element. And on the server side, Form.clean() will also check the length of any char fields.



              Finally, the database will throw an error (if you have created and applied a new migration after changing the field). But the specific behaviour here depends on the database backend.



              Client side validation is just a usability feature. All data coming from the client must also be validated on the server, since client side validation can be bypassed by an attacker, or be turned off or unavailable in some clients.



              Django's validation is what you use most of the time. It has error handling and http responses built in if you use a framework/app such as django forms, django admin or django rest framework.



              The database validation is fallback when you insert some invalid data even if it's "not supposed to be possible". Errors here could result in a uncaught exception and the entire transaction will be rolled back. It's a very useful safety net when you have bugs in your django application.






              share|improve this answer




























                1














                It depends on the specific field property. In the case of max_length, it's used in several validation steps in addition to the database itself.



                The default html widget will insert a maxlength attribute in the <input> form element. And on the server side, Form.clean() will also check the length of any char fields.



                Finally, the database will throw an error (if you have created and applied a new migration after changing the field). But the specific behaviour here depends on the database backend.



                Client side validation is just a usability feature. All data coming from the client must also be validated on the server, since client side validation can be bypassed by an attacker, or be turned off or unavailable in some clients.



                Django's validation is what you use most of the time. It has error handling and http responses built in if you use a framework/app such as django forms, django admin or django rest framework.



                The database validation is fallback when you insert some invalid data even if it's "not supposed to be possible". Errors here could result in a uncaught exception and the entire transaction will be rolled back. It's a very useful safety net when you have bugs in your django application.






                share|improve this answer


























                  1












                  1








                  1






                  It depends on the specific field property. In the case of max_length, it's used in several validation steps in addition to the database itself.



                  The default html widget will insert a maxlength attribute in the <input> form element. And on the server side, Form.clean() will also check the length of any char fields.



                  Finally, the database will throw an error (if you have created and applied a new migration after changing the field). But the specific behaviour here depends on the database backend.



                  Client side validation is just a usability feature. All data coming from the client must also be validated on the server, since client side validation can be bypassed by an attacker, or be turned off or unavailable in some clients.



                  Django's validation is what you use most of the time. It has error handling and http responses built in if you use a framework/app such as django forms, django admin or django rest framework.



                  The database validation is fallback when you insert some invalid data even if it's "not supposed to be possible". Errors here could result in a uncaught exception and the entire transaction will be rolled back. It's a very useful safety net when you have bugs in your django application.






                  share|improve this answer














                  It depends on the specific field property. In the case of max_length, it's used in several validation steps in addition to the database itself.



                  The default html widget will insert a maxlength attribute in the <input> form element. And on the server side, Form.clean() will also check the length of any char fields.



                  Finally, the database will throw an error (if you have created and applied a new migration after changing the field). But the specific behaviour here depends on the database backend.



                  Client side validation is just a usability feature. All data coming from the client must also be validated on the server, since client side validation can be bypassed by an attacker, or be turned off or unavailable in some clients.



                  Django's validation is what you use most of the time. It has error handling and http responses built in if you use a framework/app such as django forms, django admin or django rest framework.



                  The database validation is fallback when you insert some invalid data even if it's "not supposed to be possible". Errors here could result in a uncaught exception and the entire transaction will be rolled back. It's a very useful safety net when you have bugs in your django application.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 10 at 20:07

























                  answered Nov 10 at 18:06









                  Håken Lid

                  10.5k62441




                  10.5k62441

























                      3














                      Django won't do anything in the situation you describe. However, if you run makemigrations, it will generate a database migration which modifies the db column to 5 characters; running this will truncate the existing values.






                      share|improve this answer


























                        3














                        Django won't do anything in the situation you describe. However, if you run makemigrations, it will generate a database migration which modifies the db column to 5 characters; running this will truncate the existing values.






                        share|improve this answer
























                          3












                          3








                          3






                          Django won't do anything in the situation you describe. However, if you run makemigrations, it will generate a database migration which modifies the db column to 5 characters; running this will truncate the existing values.






                          share|improve this answer












                          Django won't do anything in the situation you describe. However, if you run makemigrations, it will generate a database migration which modifies the db column to 5 characters; running this will truncate the existing values.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Nov 10 at 18:06









                          Daniel Roseman

                          443k41573629




                          443k41573629






























                              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%2f53241677%2fhow-does-django-maintain-consistency-between-its-logical-constraints-and-its-da%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







                              這個網誌中的熱門文章

                              Tangent Lines Diagram Along Smooth Curve

                              Yusuf al-Mu'taman ibn Hud

                              Zucchini