Helana Brock
Helana Brock

Reputation: 55

How can I combine these two model fields into one?

Let's say I have this model:

class ParticipationCount(models.Model):

    female = models.PositiveIntegerField()
    male   = models.PositiveIntegerField()

I would like to combine them permanently into:

people = models.PositiveIntegerField() 

I would like for all the existing male and female ones to both be combined into "people." As we already use this model and have data.

Here is the admin:

class ParticipationCountAdmin(admin.ModelAdmin):
    list_display = ("shift_datetime", "shift", "location", "female", "male")
    search_fields = ["location", "female", "male"]
    form = ParticipationCountForm

So, in summary, how do I combine the "male" and "female" into one field, and continue using this field from here on out, because we don't refer to genders anymore.

Upvotes: 0

Views: 1217

Answers (1)

Daniel Holmes
Daniel Holmes

Reputation: 2002

To elaborate on Daniel Roseman's comment, you can do it in the following way:

STEP 1: Add the field people to your model, like so:

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

Then run the commands python manage.py makemigrations and python manage.py migrate

STEP 2: Next, create your own migration file:

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),
    ]

Then run the command python manage.py migrate

STEP 3: Remove the male and female fields, like so:

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

Then run the commands python manage.py makemigrations and python manage.py migrate


For more info on writing your own migrations, take a look at the docs.

Upvotes: 3

Related Questions