Hiddenguy
Hiddenguy

Reputation: 537

Duplicate key value violates unique constraint Django

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.

models.py

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)

views.py

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)

UPDATE

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.

Upvotes: 1

Views: 1931

Answers (2)

Hari
Hari

Reputation: 1623

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.

Upvotes: 4

tIrU
tIrU

Reputation: 55

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

Upvotes: -1

Related Questions