Home > other >  How to copy the data in old col to new col with only unique values?
How to copy the data in old col to new col with only unique values?

Time:01-18

I'm trying to create a new unique field called last_name_unique. I need to copy the data from last_name to last_name_unique. The new field can be nullable so we can add null for the repeated values.

For example, if there are two last names with value "Junior", under the last_name_unique there will be one value "Junior" and then null for the other "Junior" value. The first "Junior" value should be saved and the second one should be saved as null.

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

Any idea how to achieve this would be appreciated.

CodePudding user response:

As I know so far, it would be a good approach to implement signals:

your_app/models.py

class Person(models.Model):
    ...
    last_name_unique = models.CharField(max_length=30, default=None, null=True)

your_app/apps.py

from django.apps import AppConfig

class YourAppConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'  # if your Django version uses it
    name = 'your_app'

    def ready(self):
        import your_app.signals

your_app/signals.py

from django.db.models.signals import post_save
from django.dispatch import receiver
from your_app.models import Person


@receiver(post_save, sender=Person)
def add_last_name_unique(sender, instance, created, **kwargs):
    if created:
        if not Person.objects.filter(last_name=instance.last_name):
            instance.last_name_unique = instance.last_name
            instance.save()

CodePudding user response:

Set the default value of last_name_unique to null

last_name_unique = models.CharField(max_length=30,default=None) 

and after that you can run a code something like this:

q=mymodel.objects.all()
for e in q:
    if not len(q.filter(last_name=e.last_name))>=2:
                e.last_name_unique=e.last_name
                e.save()

The above code will copy all unique last names, now you haven't been told which object has to save 'junior' as unique_last_name (i.e the latest saved one or the other one) if there are 2 or more fields with the last name 'junior'.

  •  Tags:  
  • Related