简体   繁体   中英

FOREIGN KEY constraint failed delete django

Sorry for my english. I spend 2 days but cant understand why i have error:

FOREIGN KEY constraint failed

I use python 2.7 everything works fine, then i update to python 3.5.2 and now when i try delete i have this error. I have models as below:

class Auction(models.Model):
    sealers = models.ForeignKey(User, related_name="sealers", on_delete=models.CASCADE)
    buyer = models.ManyToManyField(User, related_name='buyer')
    product_in_auction = models.ForeignKey(Product, related_name='product_in_auction', null=True, blank=True, on_delete=models.CASCADE)
    name_auction = models.CharField(max_length=64, blank=False, null=False)
    description = models.TextField(blank=True, null=True, default=None)
    conf_propose = models.OneToOneField('Propose', null=True, blank=True, related_name='confirm_proposition', on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated_at = models.DateTimeField(auto_now_add=False, auto_now=True)

    class Meta:
        verbose_name = 'Auction'
        verbose_name_plural = 'Auctions'

    def __str__(self):
        return "%s" % (self.name_auction)


class Propose(models.Model):
    buyer = models.ForeignKey(User, related_name="propositions_of_auction", on_delete=models.CASCADE, null=True, blank=True)
    auction = models.ForeignKey(Auction, related_name="propositions_of_auction", on_delete=models.CASCADE)
    bit = models.DecimalField(max_digits=10, decimal_places=2, default=0, blank=True)
    created_at = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated_at = models.DateTimeField(auto_now_add=False, auto_now=True)

    class Meta:
        verbose_name = 'Proposition of the auction'
        verbose_name_plural = 'Propositions of the auction'

    def __str__(self):
        return "%s" % (self.bit)

When i try delete some auction i have error

FOREIGN KEY constraint failed

I don't think the problem is about the python version. Just like the error says, you have Foreign key constraint. So in your Propose model you have a field called auction which is the ForeignKey of model Auction, So if you want to delete some auction instance it will affect the data in the table Propose as well.

I had this error every time I wanted to change something using administration. I was lucky not to have a big database. So I simply deleted all migrations (except __init__.py ), the database and made them again using manage.py makemigrations and manage.py migrate . This straightforward method worked for me!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM