0

I have trouble with the code architecture for adding many-to-many links when reading a file and creating new objects

models.py

class GS(models.Model):
    name = model.CharField()
    country_code = ManyToMany(Lang)

class Lang(models.Model):
    code
    name

I read the csv file and create new objects on each row

file.csv

**Name**,**Lang**
name1,US; JP; AU
name2,MX; ID; UA; CZ; ZA; HU; SK
....

The Lang model is already in the database.I.e. I need to iterate through the file and create a new instance of GS and an intermediate model to link this instance with all the appropriate Lang objects.

def handle(self, *args, **options):
    path = path_to 'file.csv'
    df = pd.read_csv(path)
    # set an empty queryset
    lang = Lang.objects.none()
    geo_segment = []
    for i, row in df.iterrows():
        # get list of language code
        lang_code = [c_c.strip(' ') for c_c in row['Lang'].split(';')] ->  [MX, ID, UA, CZ .....]
        # get appropriate Lang objects
        langs = Lang.objects.filter(code__in=lang_code)
        # fulfill lang queryset distinct 
        lang = lang | langs
        segment = GS(name=row['Name'] )
        geo_segment.append(segment)
    # create new GS instancess but without realtions with Lang objects
    GS.objects.bulk_create(geo_segment)

    #SOME NEW LOGIC

And here I'm lost, how to make the new created GS objects with all the corresponding Lang objects. In the for loop I can't do it, because the MtM link can only be created with already existing objects, and at the time of iteration GS is not yet saved in the database. Maybe I'm going the wrong way, is it possible?

Jekson
  • 2,892
  • 8
  • 44
  • 79
  • https://stackoverflow.com/questions/34090582/proper-way-to-bulk-create-for-manytomany-field-django – lucutzu33 Sep 15 '21 at 10:15
  • Yes I saw the example, I understand how to create a link MtM, I can not figure out how to link the corresponding instances. I.e. to add to the instance `GS` only the necessary instances from `lang` – Jekson Sep 15 '21 at 10:30

0 Answers0