Micah Pearce
Micah Pearce

Reputation: 1945

Django 2.0: Foreign Key Constraint

I keep getting a Foreign Key Constraint when I am trying to create a new instance of a model. I can do this in the admin just fine, but it isn't working on the code side of things. I did at one point take the this Thing model and remove to other foreign keys and put these two foreign keys in, but I don't know if that has anything to do with this error. Do you know what's creating this Foreign Key Error?

class ThingManager(models.Manager):
  def new(self,thing_a=None,thing_b=None):
    return self.model.objects.create(thing_a=thing_a, thing_b=thing_b)

class Thing(models.Model):
    thing_a= models.ForeignKey(BillingProfile, blank=False, related_name='thinga+', default=False, on_delete=models.CASCADE)
    thing_b= models.ForeignKey(BillingProfile, blank=False, related_name='thingb+',default=False, on_delete=models.CASCADE)
    thing_c = models.ForeignKey(BillingProfile, blank=True, related_name='thingc+',default=False, on_delete=models.CASCADE,null=True)
    thing_id = models.CharField(max_length=120, blank=True)

    def __str__(self):
        return self.thing_id

    objects = ThingManager()

BillingPorfile is just an extension of the User Profile

class BillingProfile(models.Model):
    user        = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
    email       = models.EmailField()

code creating the error:

bp1 = BillingProfile.objects.filter(user__email='[email protected]')
bp2 = BillingProfile.objects.filter(user__email='[email protected]')
qs = Thing.objects.new(thing_a=bp1.first(),thing_b=bp2.first())

error message:

 Traceback (most recent call last):
      File "<console>", line 1, in <module>
      File "C:myapp\src\thing\models.py", line 38, in new
        return self.model.objects.create(thing_a=thing_a, thing_b=thing_b)
      File "C:myapp\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
        return getattr(self.get_queryset(), name)(*args, **kwargs)
      File "C:myapp\lib\site-packages\django\db\models\query.py", line 417, in create
        obj.save(force_insert=True, using=self.db)
      File "C:myapp\lib\site-packages\django\db\models\base.py", line 729, in save
        force_update=force_update, update_fields=update_fields)
      File "C:myapp\lib\site-packages\django\db\models\base.py", line 759, in save_base
        updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
      File "C:myapp\lib\site-packages\django\db\transaction.py", line 212, in __exit__
        connection.commit()
      File "C:myapp\lib\site-packages\django\db\backends\base\base.py", line 261, in commit
        self._commit()
      File "C:myapp\lib\site-packages\django\db\backends\base\base.py", line 239, in _commit
        return self.connection.commit()
      File "C:myapp\lib\site-packages\django\db\utils.py", line 89, in __exit__
        raise dj_exc_value.with_traceback(traceback) from exc_value
      File "C:myapp\lib\site-packages\django\db\backends\base\base.py", line 239, in _commit
        return self.connection.commit()
    django.db.utils.IntegrityError: FOREIGN KEY constraint failed

Upvotes: 0

Views: 139

Answers (1)

Roman Yakubovich
Roman Yakubovich

Reputation: 903

Probably the problem is in the default value of thing_c. Foreign key is a reference to other table column, in this case (when neither primary key is specified explicitly in a model nor to_field attribute of ForeignKey field) to id field of BillingProfile, so it is some sort of integer, not boolean.

Change default value of thing_c foreign key to None. thing_a and thing_b defaults should be deleted actually as you don't specify null=True on these fields.

Upvotes: 1

Related Questions