0

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.

2
  • What exactly doesn't work? Any error? Shoudn't it be for i in range(1,1001) here? Commented Jan 31, 2020 at 6:45
  • I have added the error here @neverwalkaloner Commented Jan 31, 2020 at 6:48

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

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.