[英]Sql query in django. How to translate?
我有这个SQL查询:
"INSERT INTO $TABLENAME (address, count) VALUES(%s, %s) \
ON DUPLICATE KEY UPDATE count = VALUES(count) + count"
怎么把它翻译成django?
我认为您正在寻找get_or_create
https://docs.djangoproject.com/en/dev/ref/models/querysets/#get-or-create
例如,假设$ TABLENAME由称为MyModel的Django模型表示:
models.py:
class MyModel(models.Model):
address = models.CharField(max_length=300, unique=True)
count = models.IntegerField(default=0)
views.py:
new_model, created = MyModel.objects.get_or_create(address="123 1st st")
new_model.count += 1
new_model.save()
get_or_create将使用给定的属性创建一个新对象,或者如果该对象已经存在,它将返回现有对象,然后可以对其进行更新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.