简体   繁体   中英

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

Say I have a model as:

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

The entity having remark="counter" has 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.

Is there any way I can do this using only Django ORM query(using F or something else) and no Python.

If you really, really need to do this, despite all the red flags, F() functions should do the trick. Most databases implicitly convert strings and ints as required, so you can just do this:

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

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