Django模型自增和自减

huangapple go评论64阅读模式
英文:

Django Models Auto Increment And Decrement

问题

在Django模型中,我正在尝试使用自动增加和自动减少功能来保存对象。

models.Autofield(primary_key=True)

已经处理了自增的功能。然而,对于自减,我认为我需要定义一个单独的函数。是否有人有聪明的解决方案?

我的用例是在管理站点上保存故障信息。如果我们有7个故障(M01,M02,M03 .. M07),并且我们删除了M03,故障的编号,包括M04及以上,应该减少。( --> M01,M02,M03,.. M06)

英文:

I am trying in Django Models to save the objects with an Auto Increment and Auto Decrement function.

models.Autofield(primary_key=True)

is already taking the functionality for the incrementation.
However, for the decrementation I think i need to define a seperate function. Does somebody have a smart solution?

My use case is for saving Malfunctions on the administration site.
If we have e.g. 7 Malfunctions (M01, M02, M03 .. M07) and we delete M03, the numbering of the malfunctions including M04 and above should decrement. ( --> M01, M02, M03, .. M06)

答案1

得分: 1

primary_key 字段是只读的,因此您将无法对其进行减少。

https://docs.djangoproject.com/en/4.2/ref/models/fields/#primary-key

通过添加额外字段,例如 malfunction_number,并在每次删除时手动处理所有表项来扩展模型。

英文:

primary_key field is readonly so you will not be able to decrement it.

https://docs.djangoproject.com/en/4.2/ref/models/fields/#primary-key

Extend model with additional field e.g. malfunction_number and handle update of all table items manually on every delete.

答案2

得分: 0

如果你希望在每次保存模型实例时更新字段,可能还要根据其他字段的条件来更新,你可以通过子类化保存方法来实现。查看文档。请注意,你可能需要告诉超类该字段需要保存。 "如果你希望在save()方法中更新字段的值,你可能还想将该字段添加到update_fields关键字参数中。这将确保在指定update_fields时保存该字段..."

英文:

If you want a field to update every time a model instance is saved, possibly conditionally on other fields, you can do that by subclassing the save method. See the doc. Note that you may have to tell the superclass that the field needs to be saved. "If you wish to update a field value in the save() method, you may also want to have this field added to the update_fields keyword argument. This will ensure the field is saved when update_fields is specified..."

huangapple
  • 本文由 发表于 2023年7月6日 18:58:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76628105.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定