简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM