Hassan
Hassan

Reputation: 436

Django ORM - No cascading deletion of a many-to-many relationship

I'm creating a Django application (using the out of the box ORM) to maintain pizza orders. I have the following models:

class Employee(models.Model):
    name = models.CharField(max_length=50)

class PizzaPlace(models.Model):
    name = models.CharField(max_length=50)
    employees = models.ManyToManyField(Employee)

class Order(models.Model):
    description = models.CharField(max_length=50)
    pizzaplace = models.ForeignKey(PizzaPlace)
    chef = models.ForeignKey(Employee)

I'm using a modelformset_factory to maintain each Pizza Place's employees. What I want is regardless if an employee is fired or leaves a Pizza Place, the Order they fulfilled remains in tact and is available to the Pizza Place. What is currently happening is when an Employee record is deleted from a Pizza Place, the delete is cascading.

What would be the best approach to maintain the association with preserving the Order - particularly maintain that the order was fulfilled, in the past, by the Employee who was deleted even though they are not associated with the Pizza place anymore?

Upvotes: 3

Views: 3361

Answers (2)

Enrico
Enrico

Reputation: 10665

Clear the relationships before deleting the employees

e = Employee.objects.get(id=1)
e.order_set.clear()
e.delete()

I believe the order will still reference the deleted employee and you will have to deal with that, but deleting will no longer cascade delete all the orders.

Upvotes: 3

Thomas Orozco
Thomas Orozco

Reputation: 55207

You could:

  • Not delete employees that are removed from a PizzaPlace and set a flag instead
  • Use the on_delete argument to set the employee field to null: chef = models.ForeignKey(Employee, null = True, on_delete = models.SET_NULL)

Look at the options for a ForeignKey's on_delete in the django documentation to find something that suits your use case.

Upvotes: 5

Related Questions