Home > Back-end >  adding more then one data in Many to many in Django
adding more then one data in Many to many in Django

Time:08-10

I have a project I want to add() more then one data to ManyToMany field

 class Product(models.Model):
     name = models.models.CharField(Name)

 class Tags(models.Model):
     product_of_names = models.ForeignKey(Product)
     tag_name = models.models.CharField()

 class Group(models.Model):
     tag_group = models.ManyToManyField(Tags)

views.py

  def home(request, pk):
      product_name = Product.objects.get(pk=pk)
      tag = Tags.objects.filter(product_of_names=product_name)
      print(tag.id)
      >>> 1
      >>> 2
      >>> 3
      insert_data = Group.objects.create()
      insert_data.tag_group.add(tag)
      insert_data.save()

it add just one I want to add them all in ManyToMany

Thanks for any help

CodePudding user response:

You can just add more objects into .add() method.

insert_data.tag_group.add(tag_1, tag_2, tag_3)

or shorter

insert_data.tag_group.add(*tags)

You can also pass a list using .set()

list_of_tags = list(Tags.objects.filter(product_of_names=product_name))
insert_data.tag_group.set(list_of_tags)

Read the docs: https://docs.djangoproject.com/en/4.1/ref/models/relations/#django.db.models.fields.related.RelatedManager.add

  • Related