简体   繁体   English

Django - 如何计算模型发生的删除次数?

[英]Django - How to count the number of deletions that occur for a model?

I have an application that has both posting and wishlist models.我有一个同时具有发布和愿望清单模型的应用程序。 Users create posting and wishlist objects and hypothetically when they delete these objects that means they successfully bought or sold whatever the item was.用户创建发布和愿望清单对象,并且假设当他们删除这些对象时,这意味着他们成功地购买或出售了任何项目。

I want to continuously count the number of objects that are deleted for each model and I am not sure how to do it?我想连续计算每个模型删除的对象数量,但我不知道该怎么做?

This way I can keep track of how successful customers are being.通过这种方式,我可以跟踪客户的成功程度。

Any recommendations would be greatly appreciated.任何建议将不胜感激。

You have many ways to do this:你有很多方法可以做到这一点:

  1. Implement an auditing mechanism;实施审计机制; using any number of audit applications available .使用任意数量的可用审计应用程序

  2. As of django 1.9, the delete() method returns the number of objects deleted .从 Django 1.9 开始, delete()方法返回已删除对象的数量 You can store this value in a separate model and track it.您可以将此值存储在单独的模型中并对其进行跟踪。

  3. Don't actually delete, but implement a "soft-delete" which is a form of a flag that marks records as deleted but doesn't remove them from the table.不要实际删除,而是实现“软删除”,这是一种标志形式,将记录标记为已删除,但不会将它们从表中删除。 You can then add an additional field to track any meta-data you would want to track for the delete option.然后,您可以添加一个附加字段来跟踪您希望为删除选项跟踪的任何元数据。 The easiest way to implement this is to override delete() on the model.实现这一点的最简单方法是覆盖模型上的delete()

One solution is to never hard delete any of the objects, but keep a boolean called "is_deleted" in your model.一种解决方案是永远不要硬删除任何对象,而是在模型中保留一个名为“is_deleted”的布尔值。 This way, you can count the number of deleted objects, and you can also count specific elements of the deleted objects.这样,您可以统计已删除对象的数量,也可以统计已删除对象的特定元素。 You might want to override the delete() fuction, see this SO question on how to do this:您可能想要覆盖delete()功能,请参阅有关如何执行此操作的SO 问题

Downside is of course that you have to store the elements.缺点当然是您必须存储元素。 Also, sometimes a delete should cascade.此外,有时删除应该级联。 You can for instance use a library like django-safedelete or django-softdelete例如,您可以使用像django-safedeletedjango-softdelete这样的库

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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