我有一个模型批量插入或增量式操作如下定义:如何做Django的ORM
class VectorSet(models.Model):
word = models.CharField(max_length=255)
weight = models.IntegerField()
session = models.ForeignKey(ResearchSession)
我想写,将采取字和ResearchSession列表的功能,在词语列表,如果它不存在每一个字,创建一个新的行权重为1,否则取该行,并通过1
到目前为止,我已经得到了这个重量增加:
def train(words, session):
for i in words:
result, created = VectorSet.objects.get_or_create(word=i, session=session,
defaults={'weight' : 1})
if not created:
result.weight = F('weight') + 1
result.save()
我相当确信有一种方法可以用一个查询来实现,但我无法弄清楚可能是什么,或者是否可以用django代码处理原始SQL。
至少相关:http://stackoverflow.com/问题/ 2252530/efficent-way-to-bulk-insert-with-get-or-create-in-django-sql-python-django – alecxe 2014-11-23 02:41:39
对我来说看起来非常好。 – dursk 2014-11-23 04:56:38