Anand
Anand

Reputation: 3760

How do I create a many to many relationship with an existing record?

In my Django 1.11 blog app, I have a many to many relationship between authors and posts.

# models.py

class Post(models.Model):
  title = models.CharField(max_length=200)


class Author(models.Model):
  name = models.CharField(max_length=200)
  posts = models.ManyToManyField(Post, related_name='authors')

I could create a post with an author as follows:

$ post = Post.objects.create(title='My post')
$ post.authors.create(name='John Doe')

But how can I create a post and author explicitly and connect them through the association?

$ post = Post.objects.create(title='My post')
$ author = Author.create(name='John Doe')
$ post.authors.????(author)

If I call post.authors.get_or_create(name='John Doe') it would create a new author, which is not what I want.

I could access the join table directly by making it a separate model (PostAuthor), but is there a way to connect an existing author to the post through the QuerySet API?

Upvotes: 0

Views: 46

Answers (1)

Igor Belo
Igor Belo

Reputation: 738

Try this:

post.authors.add(author)

Upvotes: 1

Related Questions