I came up with this problem, when I was creating my app. So whenever I add first comment the problem doesn't appear, but when I try do it second time I get this error:

duplicate key value violates unique constraint "tripplanner_discussion_author_id_key" DETAIL: Key (author_id)=(1) already exists.

I've tried to put unique=False to models.py, but it didn't help at all.


class Discussion(models.Model):
    author = models.OneToOneField(User, on_delete=models.CASCADE, unique=False)
    group = models.ForeignKey(Trip, on_delete=models.CASCADE, unique=False)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)


class DiscussionView(LoginRequiredMixin, CreateView):
    model = Discussion
    template_name = 'tripplanner/discussion.html'
    fields = ['text']
    success_url = '/'

    def form_valid(self, form):
        form.instance.author = self.request.user
        form.instance.group = self.trip
        return super(DiscussionView, self).form_valid(form)


When I logged to another user, the problem disappeared for one post, then it reoccured. So the problem to solve is to make this author_id unique.

2 Answers

N.HariHaraSudhan On Best Solutions

In Django

A one-to-one relationship. Conceptually, this is similar to a ForeignKey with unique=True

If you check the source code OneToOneField., it sets the unique in init.

I think you should use ForeignKey instead of OneToOne.

Community On

Try to remove unique = False then do make migrations & migrate it. if already migrations is there and remove migrations and caches for that applications and remove that id in admin page then do it may work