I have such a data model with topic and entry:
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] + "..."
I intend to retrieve the entries whose topic is questions
and title starts with numerals,
then change the unqualified titles to
the qualified title which I set is the first line retrieved from entry's text.
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']
Replace the integer with the first line of entry's text as the title:
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()
I am novice of Django, and wondering:
entry.save()
is implemented multiple times, could all the changes be saved in one go?did you tried to operate with transactions?
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()
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加