[Answered ]-How to populate model with having model django?

1πŸ‘

βœ…

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

           
πŸ‘€SamSparx

Leave a comment