dimanche 30 août 2020

Detect and Deleted Duplicate addresses in Django. Foreign key constraint failed Error

I am creating a Billing Platform for my Web Control Panel(https://github.com/sbsarnava/HostingEcom/). In the checkout page, when saving an instance of BillingAddress Model, in a post_save signal a code is run to check the instance against previously saved instances, if it is a duplicate then, The Order model references to the duplicate BillingAddress Instance and the current instance is deleted. The Code is not working and is raising a Foreign Key Constraint Error. I am nub, please help !. Please Look into my github repo for full structure of the project. My signals.py file :-

from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from .models import BillingAddress


@receiver(post_save, sender=BillingAddress)
def dont_save_if_all_fields_matching(sender, instance, created, **kwargs):
    if created:
        previousBilling = BillingAddress.objects.all()
        currentBilling = BillingAddress.objects.get(id=instance.id)
        print('From the Signal: ')
        print(instance.id)
        range1 = 10
        range2 = len(previousBilling)
        match = [[False] * range1] * range2
        c1 = 0
        for i in range(len(previousBilling)):
            if previousBilling[i].firstname == instance.firstname:
                match[c1][0] = True
            if previousBilling[i].lastname == instance.lastname:
                match[c1][1] = True
            if previousBilling[i].phonenumber == instance.phonenumber:
                match[c1][2] = True
            if previousBilling[i].email == instance.email:
                match[c1][3] = True
            if previousBilling[i].address1 == instance.address1:
                match[c1][4] = True
            if previousBilling[i].address2 == instance.address2:
                match[c1][5] = True
            if previousBilling[i].city == instance.city:
                match[c1][6] = True
            if previousBilling[i].country == instance.country:
                match[c1][7] = True
            if previousBilling[i].state == instance.state:
                match[c1][8] = True
            if previousBilling[i].pincode == instance.pincode:
                match[c1][9] = True
            c1 += 1
        print('Match:')
        print(match)
        sort = [True] * len(match)

        for i in range(len(match)):
            for j in range(len(match[i])):
                if match[i][j] == False:
                    sort[i] = False
                else:
                    continue
        print('Sort:')
        print(sort)
        for i in range(len(sort)):
            if i == True:
                # relatedOrder = currentBilling.order
                # relatedOrder.billingAddress = BillingAddress.objects.get(id=i)
                # relatedOrder.save()
                # currentBilling.delete()
                relatedOrder = instance.order_set.get(billingAddress=instance)
                currentBilling.order_set.clear()
                relatedOrder.billingAddress_id = i
                relatedOrder.save()
                instance.delete()
                return

My Billing Model and Order Model :-

class BillingAddress(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    firstname = models.CharField(max_length=200)
    lastname = models.CharField(max_length=200)
    phonenumber = models.CharField(max_length=20)
    email = models.EmailField(blank=True, null=True)
    address1 = models.CharField(max_length=1000)
    address2 = models.CharField(max_length=1000, blank=True, null=True)
    city = models.CharField(max_length=100, blank=True, null=True)
    country = models.CharField(max_length=100)
    state = models.CharField(max_length=100)
    pincode = models.IntegerField()
    saveAddress = models.BooleanField(default=False, null=True)

    def __str__(self):
        return self.user.username


class Order(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT)
    orderId = models.CharField(max_length=10, default=randomNumber(), unique=True)
    cartItems = models.OneToOneField(Cart, on_delete=models.CASCADE)
    created_date = models.DateTimeField(default=datetime.now)
    placed_date = models.DateTimeField(null=True, blank=True)
    updated_date = models.DateTimeField(auto_now=True)
    ordered = models.BooleanField(default=False)
    billingAddress = models.ForeignKey(BillingAddress, null=True, on_delete=models.SET_NULL)
    status = models.CharField(choices=ORDER_STATUS, default='processing', max_length=11)

    def __str__(self):
        return f"{self.user} - {self.placed_date}"



Aucun commentaire:

Enregistrer un commentaire