S
S
sortfact3332021-03-06 14:08:06
Django
sortfact333, 2021-03-06 14:08:06

How to add a ManyToManyField to a field?

I created a ManyToManyField field

class Picture(models.Model):
  link = models.CharField('picture_link', max_length=200)
  def __str__(self):
    return self.link

class MyModel(models.Model):
     picture = models.ManyToManyField(Picture, blank=True)

And I'm trying to add a model to the field
for pic in arr:
  _picture = pic.text
  try :
    picture = Picture.objects.get(link = _picture)
  except:
    picture = Picture(link = _picture)
    picture.save()
  mymodel.picture.add(picture)

But I am getting an error
Cannot add "<Picture: https://nndd.com/wa-data/public/shop/products/29/13/1329/images/538/538.602x0.jpg>": instance is on database "None", value is on database "default"

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question