Home > Net >  How to pass multiple integers to ManyToMany Field present in the list in Django
How to pass multiple integers to ManyToMany Field present in the list in Django

Time:01-08

I want add this product to both category, how to do it

class Category(models.Model):
    name = models.CharField(max_length=500)
    image = models.ImageField(upload_to='categories', default='default.png')

class Products(models.Model):
    name = models.CharField(max_length=500)
    category_id = models.ManyToManyField(Category, default='')
category_id = [4, 6]

 product, created = Products.objects.get_or_create(name =data['Casual Red Shirt'], 
                              product.category_id.add()

CodePudding user response:

Try this

category_id = [4, 6]
product, created  = Products.objects.get_or_create(name =data['Casual Red Shirt'], 

product.category_id.add(* category_id)
  •  Tags:  
  • Related