如何将这两个模型字段组合为一个?

时间:2019-06-18 14:54:59

标签: python django django-models django-admin

假设我有这个模型:

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

因此,总而言之,我如何将“男性”和“女性”合并到一个字段中,并从现在开始继续使用该字段,因为我们不再参考性别

1 个答案:

答案 0 :(得分:2)

要详细说明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


有关编写自己的迁移的详细信息,请查看docs