0

I had such a problem here, when I ask a question he does not save and this error pops up: "Django: IntegrityError: column user_id is not unique". Tell me what the problem is.

Here my models.py

class Question(models.Model):
    title = models.CharField(max_length=120)
    content = models.TextField()
    pub_date = models.DateTimeField(blank=True, null=False, auto_now_add=True)
    views = models.IntegerField(default=0)
    slug = models.SlugField(max_length=240, blank=True)
    tag = TaggableManager()
    user = models.OneToOneField(User, unique=True)

    def __unicode__(self):
        return self.title


    def save(self, **kwargs):
        if not self.pk:
            self.date_added = date.today()

        if self.title and not self.slug:
            self.slug = slugify(self.title)

        super(Question, self).save(**kwargs)

views.py

def ask(request):
    if request.method == 'POST':
        form = AskForm(request.POST)
        if form.is_valid():
            question = form.save(commit=False)
            question.user = request.user
            question.save()
            form.save_m2m()
            return redirect('/question/one_question/' + str(question.id))
    return HttpResponseBadRequest()

Traceback

Exception Type: IntegrityError at /question/ask/
Exception Value: column user_id is not unique
Yossi
  • 11,778
  • 2
  • 53
  • 66
  • 2
    Why is this a surprise to you? You have a OneToOneField from Question to User, which means that each User is only allowed *one* question. Adding any more will lead to the error you see. – Daniel Roseman Sep 14 '14 at 09:27
  • The way you have setup your model, a user can only ask one question - so after they asked the first question, you cannot add any more `Question`s for that user. Is this what you want to do? – Burhan Khalid Sep 14 '14 at 09:27

1 Answers1

1

You need to change your Question model, as @DanielRoseman says you should change the OneToOneField you're using:

class Question(models.Model):
    # ... ... .. other fields .... ....
    user = models.OneToOneField(User, unique=True)

You need to change from OneToOneField to ForeignKey in case that one question can be related only with one user but an user can be related with more than one question (Many to one relation):

class Question(models.Model):
    # ... ... .. other fields .... ....    
    user = models.ForeignKey(User)

or probably ManyToManyField is the most apropiated here, in case that many answers can be related with many users:

class Question(models.Model):
    # ... ... .. other fields .... ....
    user = models.ManyToMany(User)
AlvaroAV
  • 10,335
  • 12
  • 60
  • 91