0

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'),)
2
  • Where is model? Commented Sep 17, 2019 at 8:20
  • Models uploaded @NishantNawarkhede, forgot it. Commented Sep 17, 2019 at 8:24

1 Answer 1

2

I think you need to you force_insert=True,

newprofilelan.save(force_insert=True)
Sign up to request clarification or add additional context in comments.

2 Comments

Will give a try. Thanks
Worked like a charm, thanks! Any explanation on why it doesn't insert by default when creating and saving an object? I'm curious...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.