简体   繁体   中英

Django - logical delete

I want to make the following modification to the Django framework.

I want it to create a "deleted" field for each model I create.

I want it to be checked as deleted when I delete it from the admin page instead of being physically deleted.

I do not want these records checked as deleted to be listed.

I'm new to Django, I'm seeing if I can do what I want to do with it easily. I need this change because it's the way we currently work.

So far these are the changes I have made, I would like to understand how the whole Django framewok works inside but I'm so far from that, is there any documentation online which explains clearly how the inside framework parts/files/modules/classes work together, the specific role of each one, etc

In the base.py file, in the modelbase class, below this code,

for obj_name, obj in attrs.items():
new_class.add_to_class(obj_name, obj)

I added,

from django.db import models
    new_class.add_to_class('deleted', models.BooleanField())

When it creates a model it adds the "deleted" field to it.

In the base.py file, in the save method, I changed what it was there for

self.deleted = True
self.save()

So, now it check as deleted a record instead of physically delete it.

Now what I want is those records not to be listed.

I don't understand why you're modifying the framework code instead of putting your deleted field in a model base class that all of your models extend from.

Nevertheless, a nice way to filter those records out would be to add a custom manager to the model (or your base model class, if you choose to create one). To this manager, override the get_query_set method as described here . In your overridden method, add a exclude(deleted=True) filter.

Take a look at the Django-logicaldelete app, You just inherit your models from their provided Model class and you get Logical delete for all of them.

It comes with an adminModel as well so you can manage logically deleted models there too.

  1. Override the delete() method in your model class, set the deleted attribute there
  2. Create a custom manager which will filter by deleted attribute and set it as the default one (objects = MyDeletedManager)

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