Ad

How Can I Create Objects In A For-loop In Python?

- 1 answer

I'm trying to create some objects in database through a for loop in python, but when I try, it only inserts last one.

This is the code I have, where 'langssplit' is a list, the result of spliting a string like '2-3' (the pks of the Language rows in the table). I need to create and insert an object into the database for each element on the list, but it only saves the last one. The newprofile is an object I have already created.

langsparam = request.GET.get('langs', '')
langssplit = langsparam.split('-')
for lan in langssplit:
        lang = Languages.objects.filter(pk=lan).first()
        newprofilelan = ProfilesLanguages(profile=newprofile, language=lang)
        newprofilelan.save()

What am I doing wrong?

Thanks for any help!

UPDATE WITH MODELS

class Profiles(models.Model):
    alias = models.CharField(max_length=40)
    mail = models.CharField(max_length=255)
    mainimg = models.ForeignKey(Multimedia, models.DO_NOTHING)
    birthdate = models.DateTimeField(blank=True, null=True)
    country = models.CharField(max_length=30, blank=True, null=True)
    password = models.CharField(max_length=255)
    terms = models.IntegerField(blank=True, null=True)
    device_token = models.CharField(max_length=500)

    class Meta:
        managed = False
        db_table = 'profiles'

class Languages(models.Model):
    name = models.CharField(max_length=30)

    def natural_key(self):
        return (self.pk, self.name)

    class Meta:
        managed = False
        db_table = 'languages'

class ProfilesLanguages(models.Model):
    profile = models.ForeignKey(Profiles, models.DO_NOTHING, primary_key=True)
    language = models.ForeignKey(Languages, models.DO_NOTHING)

    class Meta:
        managed = False
        db_table = 'profiles_languages'
        unique_together = (('profile', 'language'),)
Ad

Answer

I think you need to you force_insert=True,

newprofilelan.save(force_insert=True)
Ad
source: stackoverflow.com
Ad