简体   繁体   中英

How can I create objects in a for-loop in python?

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'),)

我认为您需要force_insert=True

newprofilelan.save(force_insert=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM