我有一个主题和条目的数据模型:
class Topic(models.Model):
"""A topic the user is learning about."""
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User)
def __str__(self):
"""Return a string representation of the model."""
return self.text
class Entry(models.Model):
"""Something specific learned about a topic"""
topic = models.ForeignKey(Topic)
title = models.CharField(max_length=200)
text = models.TextField()
tags = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'entries'
def __str__(self):
"""Return string representation of the model"""
return self.text[:50] + "..."
我打算检索主题为questions
且标题以数字开头的条目
然后将不合格的标题更改为
我设置的合格标题是从条目文本中检索到的第一行。
entries = (Entry.objects
.filter(topic__text="Questions")
.filter(title__regex=r"^\d+"))
In[63]: [entry.title for entry in entries]
Out[63]: ['1', '1', '1', '1', '1']
将整数替换为第一行条目的文本作为标题:
def first_line(text): return re.search(r".+", text).group()
for entry in entries:
new_title = first_line(entry.text)
setattr(entry, 'title', new_title)
entry.save()
我是Django的新手,并且想知道:
entry.save()
多次实施,是否可以一次性保存所有更改? 答案 0 :(得分:1)
def first_line(text):
return re.search(r".+", text).group()
@transaction.commit_manually
def manual_transaction():
entries = Entry.objects
.filter(topic__text="Questions")
.filter(title__regex=r"^\d+")
for record in entries:
record.title = first_line(record.text)
record.save()
transaction.commit()