我有django 1.10项目。我有一个模型反馈:
/// <summary>
/// Represents an activity log filter options.
/// </summary>
public class ActivityLogFilterOptions
{
/// <summary>
/// Gets or sets the device ids to which the activity logs to be fetched.
/// </summary>
public string DeviceIds { get; set; }
/// <summary>
/// Gets or sets the start date for of the search.
/// </summary>
[DateTimeCompare("ToDate",
ValueComparison.IsLessThan, ErrorMessage = "From date must be earlier than end date.")]
public DateTime? FromDate { get; set; }
/// <summary>
/// Gets or sets the end date for the search.
/// </summary>
[DateTimeCompare("FromDate",
ValueComparison.IsGreaterThan, ErrorMessage = "To date must be later than from date.")]
public DateTime? ToDate { get; set; }
/// <summary>
/// Gets or set the page index.
/// </summary>
[Required]
[Range(0, int.MaxValue)]
public int? PageIndex { get; set; }
/// <summary>
/// Gets or sets the maximum record count per page.
/// </summary>
[Required]
[Range(1, short.MaxValue)]
public int? RecordsPerPage { get; set; }
/// <summary>
/// Gets or sets the activity log groups.
/// </summary>
public string Groups { get; set; }
}
此模型存在且DB表的列公司由公司项目的键填充。
现在我需要在模型中添加一些新字段:
class Feedback(FirstMixin, SecondMixin, models.Model):
company = models.OneToOneField(
verbose_name='Company',
to=Company,
related_name='feedback'
)
此字段应存储公司的自定义名称。
在迁移过程中,如何使此字段的值与相关公司名称相同? 我应该更改迁移的代码,还是有一些方法可以在模型中定义它?
答案 0 :(得分:9)
是,您要更改已创建的迁移文件。 尝试使用以下解决方案
from django.db import migrations, models
from django.db.models import F
def migrate_custome_name(apps, schema_editor):
Feedback = apps.get_model("app_name","Feedback")
Feedback.objects.all().update(
custom_name=F('company'))
class Migration(migrations.Migration):
dependencies = [
------
]
operations = [
migrations.AddField(
model_name='feedback',
name='custom_name',
-- your code --
),
migrations.RunPython(migrate_custome_name), # Add this function to migrate data
]
希望这会对你有所帮助。
答案 1 :(得分:0)
您可以使用数据迁移,请参阅此处的Django文档:https://docs.djangoproject.com/en/1.10/topics/migrations/#data-migrations。 在对表格应用更改后,您需要运行设置Feedback.custom_name = Feedback.company
的操作。