python - 数据迁移以替换文本字段中单词的实例?

标签 python django data-migration

我正在编写一个数据迁移,以遍历一些用于发送通知的通用模板,目的是将“word1”的所有实例更改为“word2”。 “word1”可以出现在模板名称和正文中。目前,只有一个名称中包含“word1”的模板,因此我可以使用 if 语句轻松更改该模板,该语句获取确切的名称并将其替换为所需的名称。我遇到的问题是当“word1”出现在模板正文中时,将“word1”与“word2”交换。需要额外注意的是,正文中“word1”的出现完全独立于名称中的出现。

到目前为止,我已尝试在 for 循环中使用带有 a_notification.body.contains('word1') 的 if 语句来查找哪些通知包含该单词。我还尝试将正文拆分为单词列表,按空格字符拆分文本字段,然后使用 for 循环检查每个单词以查看它是否等于“word1”。目前,我正在尝试使用 .replace() 查找实例并将其替换为所需的单词。

迁移文件:

#Generated by Django 1.11.6 on 2019-07-08 20:05
from __future__ import unicode_literals

from django.db import migrations

def word1_to_word2(apps, schema_editor):
    notification = apps.get_model('hr', 'NotificationTemplate')
    for a_notification in notification.objects.all():
        #change the name of template that needs to be changed
        if a_notification.name == 'Name with word1':
            a_notification.name = 'Name with word2'

        #Loop through body of template and change the instances
        if 'word1' in a_notification.body in a_notification.body:
            a_notification.body.replace('word1', 'word2')
        a_notification.save()

class Migration(migrations.Migration):

    dependencies = [
        ('hr', '0013_rename_fieldA'),
    ]

    operations = [
        migrations.RunPython(word1_to_word2),
    ]

模型.py

class Notification(models.Model):

    title = models.CharField(
        max_length=100, default="UREC Message", db_index=True)
    sender = models.ForeignKey(User)

    # Recepients
    employee_recepients = models.ManyToManyField(Employee, blank=True)

    # Email Pieces
    template = models.ForeignKey(NotificationTemplate, blank=True, null=True)
    signature = models.ForeignKey(NotificationSignature, blank=True, null=True)
    date_created = models.DateTimeField(auto_now_add=True)
    date_sent = models.DateTimeField(null=True)
    body = models.TextField(blank=True)

最佳答案

这不起作用的原因是因为字符串是不可变的some_string.replace(..) 不会更改字符串,而是创建一个新字符串。

因此,您可以这样调用:

<b>a_notification.body =</b> a_notification.body.replace('word1', 'word2')

话虽如此,这是相当低效的,因为您对每个对象进行查询。自 ,您可以使用 Replace expression [Django-doc] 进行两次批量更新:

from django.db.models import Value
from django.db.models.functions import Replace

def word1_to_word2(apps, schema_editor):
    notification = apps.get_model('hr', 'NotificationTemplate')
    notification.objects.update(<b>name=Replace('name', Value('word1'), Value('word2'))</b>)
    notification.objects.update(<b>body=Replace('body', Value('word1'), Value('word2'))</b>)

关于python - 数据迁移以替换文本字段中单词的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57397824/

相关文章:

mysql - 如何导入部分xml到mysql表?

python - 根据行中值的频率过滤数据帧

python - 周期性高斯的实现

python - Django 自定义管理模型 View

mysql - Ruby On Rails 关于多对多关系的数据从 sqlite3 迁移到 mysql

upgrade - 在 WSL 发行版之间迁移数据

python - 如何在 Python 中声明一个长字符串?

python - 如何在Python中将日期列绘制为x轴并绘制y轴上的数据

python - 我是否必须将我的 django 项目复制到另一台机器上才能在其上执行 celery 任务?

python - Django:如何创建自定义 "base"模型