How can I easily mark records as deleted in Django models instead of actually deleting them?

前端 未结 5 913
长发绾君心
长发绾君心 2021-02-02 17:20

Instead of deleting records in my Django application, I want to just mark them as \"deleted\" and have them hidden from my active queries. My main reason to do this is to give

5条回答
  •  情歌与酒
    2021-02-02 18:11

    Nice question, I've been wondering how to efficiently do this myself.

    I am not sure if this will do the trick, but django-reversion seems to do what you want, although you probably want to examine to see how it achieves this goal, as there are some inefficient ways to do it.

    Another thought would be to have the dreaded boolean flag on your Models and then creating a custom manager that automatically adds the filter in, although this wouldn't work for searches across different Models. Yet another solution suggested here is to have duplicate models of everything, which seems like overkill, but may work for you. The comments there also discuss different options.

    I will add that for the most part I don't consider any of these solutions worth the hassle; I usually just suck it up and filter my searches on the boolean flag. It avoids many issues that can come up if you try to get too clever. It is a pain and not very DRY, of course. A reasonable solution would be a mixture of the Custom manager while being aware of its limitations if you try searching a related model through it.

提交回复
热议问题