I’m working on an e-commerce project using Django. I’ve got two models: Customer and Purchase. I want to keep customer info for each purchase even if they delete their account. But I’m not sure how to do this without duplicating data.
Here’s what I’ve tried:
from django.contrib.auth import get_user_model
from django.db import models
class Purchase(models.Model):
buyer_email = models.EmailField()
buyer_name = models.CharField(max_length=100)
buyer = models.ForeignKey(get_user_model(), null=True, on_delete=models.SET_NULL)
def clean(self):
if not self.buyer_name:
self.buyer_name = f'{self.buyer.first_name} {self.buyer.last_name}'
if not self.buyer_email:
self.buyer_email = self.buyer.email
def save(self, *args, **kwargs):
self.full_clean()
super().save(*args, **kwargs)
This works, but it feels redundant. Is there a better way to handle this? Or do I have to accept some data duplication to keep purchase records intact after account deletion? Any advice would be great!
Hey there Iris85! That’s an interesting challenge you’re facing. I’m curious about a few things:
Have you considered using a soft delete approach instead of actually deleting the user account? This way, you could keep all the data intact but just mark the account as inactive.
Another thought - what about creating a separate ‘PurchaseInfo’ model that stores the buyer details? You could link it to both the User and Purchase models. That way, even if a user is deleted, you’d still have their info tied to the purchase.
What’s your take on privacy regulations like GDPR? Do you need to completely erase user data upon account deletion, or is it okay to keep some info for business records?
I’m really interested to hear more about your project and how you end up solving this. Keep us posted!
I’ve encountered a similar issue in my e-commerce projects. One effective approach is to implement a ‘soft delete’ mechanism for user accounts. Instead of permanently deleting user data, you can add an ‘is_active’ boolean field to your User model. When a user ‘deletes’ their account, you simply set this field to False.
This method preserves all purchase history and associated data while respecting the user’s wish to deactivate their account. It also allows for easy account reactivation if needed. Remember to adjust your authentication system to prevent login for inactive accounts.
For GDPR compliance, you can implement a separate process to truly delete user data after a specified retention period. This gives you time to maintain necessary business records while eventually complying with data erasure requests.
hey iris85, tried a separate purchasehistory model? it stores buyer info and links to purchases, not directly to users.
when an account is deleted, the record stays intact. maybe not as messy? just a thought - lmk wdyt!