0

In my django app, my model looks like:

class Tag(models.Model):
    title = models.CharField(max_length=50,)

class Publication(models.Model):
    title = models.CharField(max_length=200,)
    tags = models.ManyToManyField(Tag, blank=True, related_name="publications", null=True)

Let's say have 2 tags in my Tag table: "dogs" and "cats." Let's say my existing publication "Pets" has only the tag "dogs" on it. How can I add the existing "cats" tag to "Pets?"

In the Django docs https://docs.djangoproject.com/en/dev/ref/models/instances/, I saw the following example for updating a db item:

product.name = 'Name changed again'
product.save(update_fields=['name'])

But I don't see anything for updating a many-many field. How would I do this?

jac300
  • 5,182
  • 14
  • 54
  • 89

1 Answers1

0
# let publication be your existing Pets publication instance
cats_tag, created = Tag.objects.get_or_create(title='cats')
publication.tags.add(cats_tag)
Peter DeGlopper
  • 36,326
  • 7
  • 90
  • 83