Search code examples
sqldjangodatabasemodel

How to populate model with having model django?


I have model People:

with name, phone email, address fields

using Django's management commands I want populate Contact model with the same fields

command file: from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = 'Sorting leads '

    def handle(self, *args, **kwargs):
        pass

1.Multiple People with the same name and phone number should be merged together, so the resulting Contact contains all emails and addresses from merged Leads. 2. Multiple People with the same name, but different phone number and e-mail should be saved as separate contacts

How have I do it ? Should I do with raw sql or there is better solution.


Solution

  • I don't think you need to go to raw sql. From your description you can do this fairly easily within the ORM

    #Add this import to top
    from django.db.models import Value, BooleanField
    
    ...
    
    #get everyone, and mark them as unprocessed
    qs = People.objects.all().annotate(processed=Value(False, output_field=BooleanField()))
    
    for person in qs:
        #is there someone with the same name and phonenumber?
        person_num = qs.filter(name=person.name, phone=person.phone, processed=False).count()
        #No, they are unique, so make a contact
        if person_num == 1:
            Contact.objects.create(name = person.name, 
                phone = person.phone,
                email = person.email,
                address = person.address)
        #Yes, there is more than one, set up some lists to capture data
        elif person_num > 1:
           phone_list = []
           email_list = []
           address_list = []
           #loop through qs for people with same name and phone number and gather their details
           for p in qs:
               if (p.name == person.name) and (p.phone==person.phone) and (p.id not person.id) and not p.processed:
                   #check list before adding to avoid duplicate phones etc
                   if p.phone not in phone_list:
                       phone_list.append(p.phone)
                   if p.email not in email_list:
                       phone_list.append(p.email)
                   if p.address not in address_list:
                       phone_list.append(p.address)
                   p.processed = True
    
           Contact.objects.create(name = person.name,
               #stringify our lists with a ; seperator
               phone = ';'.join(str(x) for x in phone_list,
               email = ';'.join(str(x) for x in email_list,
               address = ';'.join(str(x) for x in address_list,)
       #check off this person as processed
       person.processed=True