Search code examples
djangomodelstagging

How do you save a relationship with an existing tag otherwise create the tag, in django views?


In a many to many tagging system; how do you save a photo to the name of the tag already exists and still save the photo with the rest of the tags added through the form.

class Photo(models.Model):
    title = models.TextField(blank=False, null=True)
    path = models.FileField(blank=False, null=True, upload_to='photos/')


class Tag(models.Model):
    name = models.TextField(blank=False, null=True)
    photos = models.ManyToManyField(Photo)

Heres an example from the view that will raise an error with Tag.name unique=true. Granted there exists a photo foo with a tag bar.

photo = Photo(title='foo2')
photo.save()
bar = form.data['tag'] ** this is tag bar
bar = Tag(name=bar)
bar.save() **will raise error, name bar already exists so you cannot save it
bar.photos.add(instance)

Solution

  • I apologize for reviving this old question and being contrary, but I thought it might help for me to provide a full code snippet. I've mentioned get_or_create a couple times but either you're misunderstanding me or vice versa. This code should be the same as what you wrote, except it uses Django's get_or_create rather than reinventing it and needing to catch the IntegrityError:

    instance = Photo(title=form.data['title'])
    instance.save()
    tag, created = Tag.objects.get_or_create(name=form.data['tags'])
    tag.photos.add(instance)
    return HttpResponse("Succesful Upload with Tags")
    

    Hope this helps. :-)