code_freak
code_freak

Reputation: 45

Insert data in model using loop

model.py

class Tag(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name


class Question(models.Model):
    name = models.CharField(max_length=255)
    Tag_name = models.ManyToManyField(Tag)

    def __str__(self):
        return self.name

I want to enter more than 10000 data in Question model so i am using loop for this, but it did not work, how can i enter data using loop in Question Model.

I tried:

for i in range(1,3):
    p = Question(name='a'+str(i),Tag_name = 2) #id of tag and
    p.save()

Error:

  File "<console>", line 1, in <module>
  File "filename", line 480, in __init__
  _setattr(self, prop, kwargs[prop])
  File "filename", line 537, in __set__
% self._get_set_deprecation_msg_params(),
  TypeError: Direct assignment to the forward side of a 
  many-to-many set is  prohibited. 
  Use Tag_name.set() instead.

I know i am doing wrong.

Upvotes: 0

Views: 187

Answers (2)

neverwalkaloner
neverwalkaloner

Reputation: 47354

You should use add method to add object to many-to-many relations. Something like this:

tag = Tag.objects.get(pk=2)
for i in range(1,3):
    p = Question(name='a'+str(i),Tag_name = 2) #id of tag and
    p.save()
    p. Tag_name.add(tag)

Or using reverse relation:

tag = Tag.objects.get(pk=2)
for i in range(1,3):
    p = tag.question_set.create(name='a'+str(i))

Note you should use snake case for class attributes name. So better to rename Tag_name to just tags for example:

tags = models.ManyToManyField(Tag)

Upvotes: 2

Mirza715
Mirza715

Reputation: 420

Do this:

tag = Tag.object.get(id=2)
for i in range(1,3):
    p = Question(name='a'+str(i)))
    p.save()
    p.Tag_name.add(tag)

Upvotes: 0

Related Questions