python - 如何将这两个模型字段合并为一个?
问题描述
假设我有这个模型:
class ParticipationCount(models.Model):
female = models.PositiveIntegerField()
male = models.PositiveIntegerField()
我想将它们永久组合成:
people = models.PositiveIntegerField()
我希望所有现有的男性和女性都合并为“人”。因为我们已经使用了这个模型并且有数据。
这是管理员:
class ParticipationCountAdmin(admin.ModelAdmin):
list_display = ("shift_datetime", "shift", "location", "female", "male")
search_fields = ["location", "female", "male"]
form = ParticipationCountForm
所以,总而言之,我如何将“男性”和“女性”合并到一个字段中,并从这里开始继续使用这个字段,因为我们不再提到性别了。
解决方案
要详细说明 Daniel Roseman 的评论,您可以通过以下方式进行:
第 1 步:将字段添加people
到模型中,如下所示:
class ParticipationCount(models.Model):
female = models.PositiveIntegerField()
male = models.PositiveIntegerField()
people = models.PositiveIntegerField()
然后运行命令python manage.py makemigrations
和python manage.py migrate
第 2 步:接下来,创建您自己的迁移文件:
def set_people(apps, schema_editor):
ParticipationCount = apps.get_model('your_app', 'ParticipationCount')
for row in ParticipationCount.objects.all():
row.people = row.male + row.female
row.save()
class Migration(migrations.Migration):
dependencies = [
('your_app', '...'), # fill in your previous migration number
]
operations = [
migrations.RunPython(set_people),
]
然后运行命令python manage.py migrate
第 3 步:删除male
和female
字段,如下所示:
class ParticipationCount(models.Model):
people = models.PositiveIntegerField()
然后运行命令python manage.py makemigrations
和python manage.py migrate
有关编写自己的迁移的更多信息,请查看文档。
推荐阅读
- laravel - 在 DirectAdmin 服务器中配置 Laravel 项目
- windows - 如何将 JSON 文件中的数据从批处理文件插入 SQLite 数据库
- go - 在 Go 中计算累积分布函数,类似于 Python 的 binom.cdf(max(0, k-1), n, p)
- python - 如何仅在列的空单元格中添加值,这些值取决于另一列的值
- quarkus - Quarkus prometheus 百分位数在较长的指标更新时间后仍然归零
- dart - 动态单例初始化(取决于参数)
- amazon-web-services - 如何在 ecs 中部署后端和前端应用程序?
- javascript - 在代码中包含 @popperjs/core 和 eslint 时如何修复意外的 Webpack 错误
- c# - 如何使用 AXE_Selenium 跨所有规则运行可访问性测试
- java - 序列不在 oracle 表上的一行中