首页 > 解决方案 > 如何将这两个模型字段合并为一个?

问题描述

假设我有这个模型:

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

所以,总而言之,我如何将“男性”和“女性”合并到一个字段中,并从这里开始继续使用这个字段,因为我们不再提到性别了。

标签: pythondjangodjango-modelsdjango-admin

解决方案


要详细说明 Daniel Roseman 的评论,您可以通过以下方式进行:

第 1 步:将字段添加people到模型中,如下所示:

class ParticipationCount(models.Model):
    female = models.PositiveIntegerField()
    male   = models.PositiveIntegerField()
    people = models.PositiveIntegerField() 

然后运行命令python manage.py makemigrationspython 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 步:删除malefemale字段,如下所示:

class ParticipationCount(models.Model):
    people = models.PositiveIntegerField() 

然后运行命令python manage.py makemigrationspython manage.py migrate


有关编写自己的迁移的更多信息,请查看文档


推荐阅读