[Fixed]-How to set value of a ManyToMany field in Django?

25👍

It looks like the problem here is that you’re trying to add something to the M2M table before it’s actually created in the database.

When you run post = Posts() you create an object in memory, but not in the database. So when you then try to add a new entry to the M2M table there is nothing to reference. (Remember that declaring an M2M field causes the creation of a new table with records that point to both ends of the relationship.)

The solution is to run post.save() before trying to add to the M2M table. (The Django admin is doing this for you behind the scenes.)

So try something like this:

post = Posts()

# now set up the post (title, name, etc.)

post.save() # adds a new entry to the Posts table

post.post_tagid.add(tag) # now that your post exists in the DB this should work

5👍

You should read official django docs on Many-to-many relationships.

In your case following code should help:

# Post object
post= Posts.objects.get(id=1)

# Two tag objects
tag1 = Tags.objects.get(id=1)
tag2 = Tags.objects.get(id=2)


# Add tag objects to Post object
post.post_tagid.add(tag1, tag2)

Leave a comment