Reputation: 2843
How do I deal with foreign keys like users or usernames that could one day be deleted?
My best guess would be a CharField with Choices limited to the Referennced Field, since deleting a ForeignKey would lead to cascade deletion.
I want to conserve eg the Name of the User related to the object even if the original User object was deleted.
Would something like this work:
def set_user_name(self):
self.user_name = self.user.name
return None
user = models.ForeignKey(User,
blank=True,
null=True,
on_delete=models.SET(set_user_name))
user_name = models.CharField(max_length=50, blank=True, null=True)
Upvotes: 1
Views: 308
Reputation: 30522
One of the common practices in relational databases is avoid deleting records that have (or might have) related entities and employ a "soft delete" pattern instead by adding an active = BooleanField(default=True)
or deleted = BooleanField(default=False)
field.
Django's built in User
model has an is_active
field that can be used for this purpose.
See more resources regarding soft delete in Django in the delete grid in djangopackages.org
Upvotes: 1