Create many-to-many relations with bulk_create during file reading

  django, python

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, I need help. The use of bulk_create is mandatory since the file contains a large number of records.

Source: Python Questions

LEAVE A COMMENT