IntegrityError UNIQUE constraint failed: POSTing to Django REST API, OneToOne Field












0















I'm posting to a backend Django REST API using a webapp developed in Angular 7 as front end. Basically I have a supertype model Factura for two subtypes, FacturaA and FacturaE, they are both related by a OneToOneField.



The models in question look like this:



class Factura(models.Model):
fecha = models.DateField()
contrato = models.ForeignKey(Contrato, related_name='facturas', on_delete=models.CASCADE)
pagado = models.BooleanField(default=False)

def __str__(self):
return 'Factura %s: %s - %s' % (self.id, self.fecha, self.contrato)

class FacturaE(models.Model):
factura = models.OneToOneField(
Factura,
on_delete=models.CASCADE,
primary_key=True,
)
kwh = models.DecimalField(max_digits=100, decimal_places=2)
monto = models.DecimalField(max_digits=100, decimal_places=2, null=True, blank=True)

def save(self, *args, **kwargs):
#calcula el monto
if self._state.adding is True:
self.monto = float(self.kwh) * 4.0588
super().save(*args, **kwargs)
super().save(*args, **kwargs)

class Meta:
verbose_name = 'Factura Electrica'
verbose_name_plural = 'Facturas Electricas'

def __str__(self):
return 'Electricidad: %s - %s' % (self.factura, self.monto)


In my frontend app, I POST by first creating a supertype object Factura, and then using the added key to post a FacturaE like so:



  addFactura(fecha: Date, kwh: number, monto: number) {
this.factura = new Factura(0, fecha, false, this.id);
this.pagoService.addFactura(this.factura).subscribe(f => {
this.facturaElectrica = new FacturaEAdd(f.id, kwh, monto);
this.pagoService.addFacturaElectrica(this.facturaElectrica).subscribe();
});
}


Adding a Factura followed by a FacturaE manually in the Django Admin produces no error, however doing this manually through the API or through my frontend app gives me the following error.



django.db.utils.IntegrityError: UNIQUE constraint failed: CasadelaAPI_facturae.factura_id.



Despite this error, and despite returning a 500 HTTP Status Code, the object is still created regardless of the method I use. I would like to know what's causing the error and how to fix it.



Edit:



Solved, super being called twice in save() method overwrite, backend was trying to save the FacturaE object twice, the second super().save(*args, **kwargs) was producing the error










share|improve this question





























    0















    I'm posting to a backend Django REST API using a webapp developed in Angular 7 as front end. Basically I have a supertype model Factura for two subtypes, FacturaA and FacturaE, they are both related by a OneToOneField.



    The models in question look like this:



    class Factura(models.Model):
    fecha = models.DateField()
    contrato = models.ForeignKey(Contrato, related_name='facturas', on_delete=models.CASCADE)
    pagado = models.BooleanField(default=False)

    def __str__(self):
    return 'Factura %s: %s - %s' % (self.id, self.fecha, self.contrato)

    class FacturaE(models.Model):
    factura = models.OneToOneField(
    Factura,
    on_delete=models.CASCADE,
    primary_key=True,
    )
    kwh = models.DecimalField(max_digits=100, decimal_places=2)
    monto = models.DecimalField(max_digits=100, decimal_places=2, null=True, blank=True)

    def save(self, *args, **kwargs):
    #calcula el monto
    if self._state.adding is True:
    self.monto = float(self.kwh) * 4.0588
    super().save(*args, **kwargs)
    super().save(*args, **kwargs)

    class Meta:
    verbose_name = 'Factura Electrica'
    verbose_name_plural = 'Facturas Electricas'

    def __str__(self):
    return 'Electricidad: %s - %s' % (self.factura, self.monto)


    In my frontend app, I POST by first creating a supertype object Factura, and then using the added key to post a FacturaE like so:



      addFactura(fecha: Date, kwh: number, monto: number) {
    this.factura = new Factura(0, fecha, false, this.id);
    this.pagoService.addFactura(this.factura).subscribe(f => {
    this.facturaElectrica = new FacturaEAdd(f.id, kwh, monto);
    this.pagoService.addFacturaElectrica(this.facturaElectrica).subscribe();
    });
    }


    Adding a Factura followed by a FacturaE manually in the Django Admin produces no error, however doing this manually through the API or through my frontend app gives me the following error.



    django.db.utils.IntegrityError: UNIQUE constraint failed: CasadelaAPI_facturae.factura_id.



    Despite this error, and despite returning a 500 HTTP Status Code, the object is still created regardless of the method I use. I would like to know what's causing the error and how to fix it.



    Edit:



    Solved, super being called twice in save() method overwrite, backend was trying to save the FacturaE object twice, the second super().save(*args, **kwargs) was producing the error










    share|improve this question



























      0












      0








      0








      I'm posting to a backend Django REST API using a webapp developed in Angular 7 as front end. Basically I have a supertype model Factura for two subtypes, FacturaA and FacturaE, they are both related by a OneToOneField.



      The models in question look like this:



      class Factura(models.Model):
      fecha = models.DateField()
      contrato = models.ForeignKey(Contrato, related_name='facturas', on_delete=models.CASCADE)
      pagado = models.BooleanField(default=False)

      def __str__(self):
      return 'Factura %s: %s - %s' % (self.id, self.fecha, self.contrato)

      class FacturaE(models.Model):
      factura = models.OneToOneField(
      Factura,
      on_delete=models.CASCADE,
      primary_key=True,
      )
      kwh = models.DecimalField(max_digits=100, decimal_places=2)
      monto = models.DecimalField(max_digits=100, decimal_places=2, null=True, blank=True)

      def save(self, *args, **kwargs):
      #calcula el monto
      if self._state.adding is True:
      self.monto = float(self.kwh) * 4.0588
      super().save(*args, **kwargs)
      super().save(*args, **kwargs)

      class Meta:
      verbose_name = 'Factura Electrica'
      verbose_name_plural = 'Facturas Electricas'

      def __str__(self):
      return 'Electricidad: %s - %s' % (self.factura, self.monto)


      In my frontend app, I POST by first creating a supertype object Factura, and then using the added key to post a FacturaE like so:



        addFactura(fecha: Date, kwh: number, monto: number) {
      this.factura = new Factura(0, fecha, false, this.id);
      this.pagoService.addFactura(this.factura).subscribe(f => {
      this.facturaElectrica = new FacturaEAdd(f.id, kwh, monto);
      this.pagoService.addFacturaElectrica(this.facturaElectrica).subscribe();
      });
      }


      Adding a Factura followed by a FacturaE manually in the Django Admin produces no error, however doing this manually through the API or through my frontend app gives me the following error.



      django.db.utils.IntegrityError: UNIQUE constraint failed: CasadelaAPI_facturae.factura_id.



      Despite this error, and despite returning a 500 HTTP Status Code, the object is still created regardless of the method I use. I would like to know what's causing the error and how to fix it.



      Edit:



      Solved, super being called twice in save() method overwrite, backend was trying to save the FacturaE object twice, the second super().save(*args, **kwargs) was producing the error










      share|improve this question
















      I'm posting to a backend Django REST API using a webapp developed in Angular 7 as front end. Basically I have a supertype model Factura for two subtypes, FacturaA and FacturaE, they are both related by a OneToOneField.



      The models in question look like this:



      class Factura(models.Model):
      fecha = models.DateField()
      contrato = models.ForeignKey(Contrato, related_name='facturas', on_delete=models.CASCADE)
      pagado = models.BooleanField(default=False)

      def __str__(self):
      return 'Factura %s: %s - %s' % (self.id, self.fecha, self.contrato)

      class FacturaE(models.Model):
      factura = models.OneToOneField(
      Factura,
      on_delete=models.CASCADE,
      primary_key=True,
      )
      kwh = models.DecimalField(max_digits=100, decimal_places=2)
      monto = models.DecimalField(max_digits=100, decimal_places=2, null=True, blank=True)

      def save(self, *args, **kwargs):
      #calcula el monto
      if self._state.adding is True:
      self.monto = float(self.kwh) * 4.0588
      super().save(*args, **kwargs)
      super().save(*args, **kwargs)

      class Meta:
      verbose_name = 'Factura Electrica'
      verbose_name_plural = 'Facturas Electricas'

      def __str__(self):
      return 'Electricidad: %s - %s' % (self.factura, self.monto)


      In my frontend app, I POST by first creating a supertype object Factura, and then using the added key to post a FacturaE like so:



        addFactura(fecha: Date, kwh: number, monto: number) {
      this.factura = new Factura(0, fecha, false, this.id);
      this.pagoService.addFactura(this.factura).subscribe(f => {
      this.facturaElectrica = new FacturaEAdd(f.id, kwh, monto);
      this.pagoService.addFacturaElectrica(this.facturaElectrica).subscribe();
      });
      }


      Adding a Factura followed by a FacturaE manually in the Django Admin produces no error, however doing this manually through the API or through my frontend app gives me the following error.



      django.db.utils.IntegrityError: UNIQUE constraint failed: CasadelaAPI_facturae.factura_id.



      Despite this error, and despite returning a 500 HTTP Status Code, the object is still created regardless of the method I use. I would like to know what's causing the error and how to fix it.



      Edit:



      Solved, super being called twice in save() method overwrite, backend was trying to save the FacturaE object twice, the second super().save(*args, **kwargs) was producing the error







      python angular django-rest-framework






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 31 '18 at 5:30







      Jose Rafael Angulo

















      asked Dec 31 '18 at 4:16









      Jose Rafael AnguloJose Rafael Angulo

      154




      154
























          1 Answer
          1






          active

          oldest

          votes


















          1














          The error is because you are violating OneOnOne attribute by creating a FactoraE with an existing Factora object assigned to it.



          So the code is throwing Unique constraint failed ....



          Please check below steps:




          • be sure that you are not trying to create another FactoraE with a Factora object that already another FactoraE is existed with same Factora Item.


          • maybe in your UI code, in service (which is not provided here) you are not passing Factora.id correctly, so it is the same as previous requests, causing this error.



          Update
          Calling super two times is not recommended and it may causing the problem.






          share|improve this answer


























          • Thank you for the help but this is not the case. When a FacturaE gets an already used Factura object assigned to it, the error reads as the first image posted above and prevents the creation of the FacturaE object, however when POSTing with a newly created Factura object that has not yet been used or assigned, the second error is showing but the object is still being created and shows up in the UI and in Django/admin.

            – Jose Rafael Angulo
            Dec 31 '18 at 5:11











          • please update your post and add pagoService from your UI

            – Reza Torkaman Ahmadi
            Dec 31 '18 at 5:16











          • And one more thing, Why you are calling super two times in your save method. One in enough. I'm not sure but check it, maybe that is the cause of error.

            – Reza Torkaman Ahmadi
            Dec 31 '18 at 5:19











          • You got it, calling super twice was causing the error. Thank you

            – Jose Rafael Angulo
            Dec 31 '18 at 5:26











          • anytime my friend:)

            – Reza Torkaman Ahmadi
            Dec 31 '18 at 5:27











          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%2f53983525%2fintegrityerror-unique-constraint-failed-posting-to-django-rest-api-onetoone-fi%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          The error is because you are violating OneOnOne attribute by creating a FactoraE with an existing Factora object assigned to it.



          So the code is throwing Unique constraint failed ....



          Please check below steps:




          • be sure that you are not trying to create another FactoraE with a Factora object that already another FactoraE is existed with same Factora Item.


          • maybe in your UI code, in service (which is not provided here) you are not passing Factora.id correctly, so it is the same as previous requests, causing this error.



          Update
          Calling super two times is not recommended and it may causing the problem.






          share|improve this answer


























          • Thank you for the help but this is not the case. When a FacturaE gets an already used Factura object assigned to it, the error reads as the first image posted above and prevents the creation of the FacturaE object, however when POSTing with a newly created Factura object that has not yet been used or assigned, the second error is showing but the object is still being created and shows up in the UI and in Django/admin.

            – Jose Rafael Angulo
            Dec 31 '18 at 5:11











          • please update your post and add pagoService from your UI

            – Reza Torkaman Ahmadi
            Dec 31 '18 at 5:16











          • And one more thing, Why you are calling super two times in your save method. One in enough. I'm not sure but check it, maybe that is the cause of error.

            – Reza Torkaman Ahmadi
            Dec 31 '18 at 5:19











          • You got it, calling super twice was causing the error. Thank you

            – Jose Rafael Angulo
            Dec 31 '18 at 5:26











          • anytime my friend:)

            – Reza Torkaman Ahmadi
            Dec 31 '18 at 5:27
















          1














          The error is because you are violating OneOnOne attribute by creating a FactoraE with an existing Factora object assigned to it.



          So the code is throwing Unique constraint failed ....



          Please check below steps:




          • be sure that you are not trying to create another FactoraE with a Factora object that already another FactoraE is existed with same Factora Item.


          • maybe in your UI code, in service (which is not provided here) you are not passing Factora.id correctly, so it is the same as previous requests, causing this error.



          Update
          Calling super two times is not recommended and it may causing the problem.






          share|improve this answer


























          • Thank you for the help but this is not the case. When a FacturaE gets an already used Factura object assigned to it, the error reads as the first image posted above and prevents the creation of the FacturaE object, however when POSTing with a newly created Factura object that has not yet been used or assigned, the second error is showing but the object is still being created and shows up in the UI and in Django/admin.

            – Jose Rafael Angulo
            Dec 31 '18 at 5:11











          • please update your post and add pagoService from your UI

            – Reza Torkaman Ahmadi
            Dec 31 '18 at 5:16











          • And one more thing, Why you are calling super two times in your save method. One in enough. I'm not sure but check it, maybe that is the cause of error.

            – Reza Torkaman Ahmadi
            Dec 31 '18 at 5:19











          • You got it, calling super twice was causing the error. Thank you

            – Jose Rafael Angulo
            Dec 31 '18 at 5:26











          • anytime my friend:)

            – Reza Torkaman Ahmadi
            Dec 31 '18 at 5:27














          1












          1








          1







          The error is because you are violating OneOnOne attribute by creating a FactoraE with an existing Factora object assigned to it.



          So the code is throwing Unique constraint failed ....



          Please check below steps:




          • be sure that you are not trying to create another FactoraE with a Factora object that already another FactoraE is existed with same Factora Item.


          • maybe in your UI code, in service (which is not provided here) you are not passing Factora.id correctly, so it is the same as previous requests, causing this error.



          Update
          Calling super two times is not recommended and it may causing the problem.






          share|improve this answer















          The error is because you are violating OneOnOne attribute by creating a FactoraE with an existing Factora object assigned to it.



          So the code is throwing Unique constraint failed ....



          Please check below steps:




          • be sure that you are not trying to create another FactoraE with a Factora object that already another FactoraE is existed with same Factora Item.


          • maybe in your UI code, in service (which is not provided here) you are not passing Factora.id correctly, so it is the same as previous requests, causing this error.



          Update
          Calling super two times is not recommended and it may causing the problem.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Dec 31 '18 at 5:27

























          answered Dec 31 '18 at 5:03









          Reza Torkaman AhmadiReza Torkaman Ahmadi

          887316




          887316













          • Thank you for the help but this is not the case. When a FacturaE gets an already used Factura object assigned to it, the error reads as the first image posted above and prevents the creation of the FacturaE object, however when POSTing with a newly created Factura object that has not yet been used or assigned, the second error is showing but the object is still being created and shows up in the UI and in Django/admin.

            – Jose Rafael Angulo
            Dec 31 '18 at 5:11











          • please update your post and add pagoService from your UI

            – Reza Torkaman Ahmadi
            Dec 31 '18 at 5:16











          • And one more thing, Why you are calling super two times in your save method. One in enough. I'm not sure but check it, maybe that is the cause of error.

            – Reza Torkaman Ahmadi
            Dec 31 '18 at 5:19











          • You got it, calling super twice was causing the error. Thank you

            – Jose Rafael Angulo
            Dec 31 '18 at 5:26











          • anytime my friend:)

            – Reza Torkaman Ahmadi
            Dec 31 '18 at 5:27



















          • Thank you for the help but this is not the case. When a FacturaE gets an already used Factura object assigned to it, the error reads as the first image posted above and prevents the creation of the FacturaE object, however when POSTing with a newly created Factura object that has not yet been used or assigned, the second error is showing but the object is still being created and shows up in the UI and in Django/admin.

            – Jose Rafael Angulo
            Dec 31 '18 at 5:11











          • please update your post and add pagoService from your UI

            – Reza Torkaman Ahmadi
            Dec 31 '18 at 5:16











          • And one more thing, Why you are calling super two times in your save method. One in enough. I'm not sure but check it, maybe that is the cause of error.

            – Reza Torkaman Ahmadi
            Dec 31 '18 at 5:19











          • You got it, calling super twice was causing the error. Thank you

            – Jose Rafael Angulo
            Dec 31 '18 at 5:26











          • anytime my friend:)

            – Reza Torkaman Ahmadi
            Dec 31 '18 at 5:27

















          Thank you for the help but this is not the case. When a FacturaE gets an already used Factura object assigned to it, the error reads as the first image posted above and prevents the creation of the FacturaE object, however when POSTing with a newly created Factura object that has not yet been used or assigned, the second error is showing but the object is still being created and shows up in the UI and in Django/admin.

          – Jose Rafael Angulo
          Dec 31 '18 at 5:11





          Thank you for the help but this is not the case. When a FacturaE gets an already used Factura object assigned to it, the error reads as the first image posted above and prevents the creation of the FacturaE object, however when POSTing with a newly created Factura object that has not yet been used or assigned, the second error is showing but the object is still being created and shows up in the UI and in Django/admin.

          – Jose Rafael Angulo
          Dec 31 '18 at 5:11













          please update your post and add pagoService from your UI

          – Reza Torkaman Ahmadi
          Dec 31 '18 at 5:16





          please update your post and add pagoService from your UI

          – Reza Torkaman Ahmadi
          Dec 31 '18 at 5:16













          And one more thing, Why you are calling super two times in your save method. One in enough. I'm not sure but check it, maybe that is the cause of error.

          – Reza Torkaman Ahmadi
          Dec 31 '18 at 5:19





          And one more thing, Why you are calling super two times in your save method. One in enough. I'm not sure but check it, maybe that is the cause of error.

          – Reza Torkaman Ahmadi
          Dec 31 '18 at 5:19













          You got it, calling super twice was causing the error. Thank you

          – Jose Rafael Angulo
          Dec 31 '18 at 5:26





          You got it, calling super twice was causing the error. Thank you

          – Jose Rafael Angulo
          Dec 31 '18 at 5:26













          anytime my friend:)

          – Reza Torkaman Ahmadi
          Dec 31 '18 at 5:27





          anytime my friend:)

          – Reza Torkaman Ahmadi
          Dec 31 '18 at 5:27


















          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%2f53983525%2fintegrityerror-unique-constraint-failed-posting-to-django-rest-api-onetoone-fi%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

          Monofisismo

          Angular Downloading a file using contenturl with Basic Authentication

          Olmecas