简体   繁体   English

如何使用 Django ORM 增加 Django CharField(包含整数)?

[英]How to increment Django CharField (containing an integer) using Django ORM?

Say I have a model as:假设我有一个 model 为:

class model(models.Model):
    remark=models.CharField(max_length=25)
    count=models.CharField(max_length=5)

The entity having remark="counter" has count="34".具有 remark="counter" 的实体有 count="34"。 I wish to retrieve entity (having remark="counter") and change its count to "35", ie cast to integer, increment it by 1, cast back to string, update.我希望检索实体(具有 remark="counter")并将其计数更改为“35”,即转换为 integer,将其递增 1,转换回字符串,更新。

Is there any way I can do this using only Django ORM query(using F or something else) and no Python.有什么方法可以只使用 Django ORM 查询(使用 F 或其他)而不使用 Python。

If you really, really need to do this, despite all the red flags, F() functions should do the trick.如果你真的,真的需要这样做,尽管有所有的危险信号,F() 函数应该可以解决问题。 Most databases implicitly convert strings and ints as required, so you can just do this:大多数数据库会根据需要隐式转换字符串和整数,因此您可以这样做:

Model.objects.filter(...).update(count=F('count')+1)

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

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