简体   繁体   中英

Django model inheritance: Delete subclass keep superclass

When dealing whith model inheritance in django is it possible to remove a instance of model subclass, without removing the superclass itself?

Using the Django example , can you remove just the Resturaunt object and retain the Place object?

Yesterday I was looking for an answer to this question and I came up with this solution, which was enough for my problem but could be scaled up as needed.

Assuming you have a Restaurant and a Place django models, the way to delete a restaurant only without touching the row inside the Place's table is creating a "fake" Restaurant model like this:

class FakeRestaurant(models.Model):
    place_ptr = models.PositiveIntegerField(db_column="place_ptr_id", primary_key=True)
    serves_hot_dogs = models.BooleanField()
    serves_pizza = models.BooleanField()

    class Meta:
        app_label = Restaurant._meta.app_label
        db_table = Restaurant._meta.db_table
        managed = False

Now, you can retrieve objects from that table as if it had no bound external relationship:

place = Place.objects.get(pk=1)
restaurant = Restaurant.objects.get(pk=1)
fake_restaurant = FakeRestaurant.objects.get(pk=1)
fake_restaurant.delete()

fake_restaurant and restaurant won't exist anymore, place will remain untouched.

Cheers, Davide

In Django 1.9 parameter keep_parents was added to model delete() function, so to keep parents just call:

restaurant.delete(keep_parents=True)

Docs: https://docs.djangoproject.com/en/1.10/ref/models/instances/#django.db.models.Model.delete

UPDATE:

Apparently, this feature is not working properly in Django 1.9, please see the comments.

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