Search code examples
pythondjangopython-3.xdjango-querysetsearchqueryset

How to insert element into a field with django


What would be the best way to insert a variable into a field in django, similar to insert element into a list in python.

I am not trying to update a record field "first_name" in the database but rather "insert" or "add" a second "first_name" from someone else in the database that share the same last name.

Ex:

First Name      Last Name
    Alan            Smith
    Eric            Jones
    Inna            Smith

Result:

First Name         Last Name
    Alan, Inna      Smith, Smith
    Eric            Jones

I am using PostgreSQL as database.

Any help would be much appreciated. Thank you.


Solution

  • This is what I came up with. Hope it helps.

    to_delete = []
    for person in Person.objects.all():
        # all people sharing a last name with person
        matches = Person.objects.filter(last_name=person.last_name)
    
        # a list with the first names
        first_names = matches.values_list('first_name', flat=True)
        # a list with the last names
        last_names = matches.values_list('last_name', flat=True)
    
        # Join them with comma as a separator e.g 'Alan, Inna'
        joined_fnames = ', '.join(first_names)
        joined_lnames = ', '.join(last_names)
    
        # set the new joined strings as persons new values
        person.first_name = joined_fnames
        person.last_name = joined_lnames
    
        # get the other record ids that have already been joined into person and add to to_delete
        ids = matches.exclude(id=person.id).values_list('id', flat=True)
        to_delete += ids
    
        person.save()
    
    # finally delete all records in to_delete
    Person.objects.filter(id__in=to_delete).delete()