列user_id的问题不是唯一的

时间:2014-09-14 09:15:10

标签: django

我在这里遇到了这样的问题,当我问一个他没有保存的问题并且弹出这个错误:“Django:IntegrityError:column user_id不是唯一的”。告诉我问题是什么。

这是我的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()

回溯

Exception Type: IntegrityError at /question/ask/
Exception Value: column user_id is not unique

1 个答案:

答案 0 :(得分:1)

您需要更改问题模型,因为@DanielRoseman说您应该更改 OneToOneField 您正在使用:

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

您需要将 OneToOneField 更改为 ForeignKey ,以防一个问题与与一个用户相关但用户可能相关多个问题(多对一关系):

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

或者 ManyToManyField 是最适合的,如果很多答案可以与很多用户相关:

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