Django - deleting an object without deleting related objects

I have two models:

class Client(models.Model): some_field = models.CharField() class Ticket(models.Model): client = models.ForeignKey(Client) 

Ticket FOREVER is on my system, but I want users to be able to delete clients they no longer want. Currently, it will delete all tickets created by Client .

  • Is this a bad idea (architecturally speaking) and should I just mark them as not_needed or something instead?
  • If this is not a bad idea, what is the best way to do this by staying DRY. I don't want to override delete() for every model that does this, but will if I need to (which is the best way to do this if this is the only way).
+4
source share
3 answers

So, this question is very old, but in case someone runs it (like me): starting with Django 1.3, you can use the on_delete parameter for ForeignKey models, as described here .

+9
source

The django.contrib.auth module must deal with the same problem in the User model. Their solution is to:

 class User(models.Model): # ... is_active = models.BooleanField(default=True) # ... 

So the โ€œremovalโ€ of a User simply sets is_active to False . Everything that works with User needs to check is_active .

For the record, I think that uninstalling Client in this case is a Bad idea .

But for the sake of argument, if you delete Client , then the associated Ticket must first become without a client. Change the model for Ticket to:

 class Ticket(models.Model): client = models.ForeignKey(Client, null=True, blank=True, related_name='tickets') 

Then, to remove a Client , do:

 for ticket in clientToDelete.tickets: ticket.client = None ticket.save() clientToDelete.delete() 

You can put this code in the Client delete method, but it will be skipped if you delete the array (i.e. based on QuerySet) of Client s.

+5
source

Personally, I think this is a bad idea (you would have records of orphan tickets). I would simply mark these clients as "not_needed" or "deleted". You also get the added benefit of being able to โ€œdeleteโ€ these clients later.

0
source

All Articles