从一个视图创建两个模型,django

时间:2014-04-17 08:42:53

标签: django django-models django-forms django-views

这看起来很明显,但我暂时还不清楚。我有三个模型:Project,Question_Text和Question。问题有项目的ForeignKey和Question_Text。我可以创建和保存Project,但是当我创建Question_Text时,我也应该从一个视图中创建一个问题。我尝试使用Question.objects.create(),然而,我在这周围的舞蹈似乎是致命的。我收到错误table project_question has no column named question_text_id。从db的角度来看,它是这样的:" question_text_id"整数NOT NULL REFERENCES" project_question_text" (" ID&#34)。 请帮忙!

我的模特:

class Project(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=40)
audience_count = models.IntegerField(default=0)
audience_ready = models.IntegerField(default=0)
pub_date = models.DateTimeField("Date Created")

def __unicode__(self):
    return self.title

class Question_Text(models.Model):
text_en = models.CharField(max_length=60, blank=True)


class Question(models.Model):
user = models.ForeignKey(User)
project = models.ForeignKey(Project)
question_text = models.ForeignKey(Question_Text)
viewed = models.BooleanField(default=False)
def __unicode__(self): 
    return self.question_text

我的观点:

def add_question(request, project_id):
a = Project.objects.get(id=project_id)

if request.method == "POST":
    f = QuestionTextForm(request.POST)
    if f.is_valid():
        c = f.save(commit=False)
        #          c.pub_date = timezone.now()
        q = Question.objects.create()
        q.question_text = c
        q.project = a
        q.save()
        c.save()

        messages.success(request, "Your question was added")

        return HttpResponseRedirect('/projects/get/%s' % project_id)

else:
    f = QuestionTextForm(request.POST) #Add request params to initialization


args = {}
args.update(csrf(request))

#    args['question'] = q
args['project'] = a
args['form'] = f

return render_to_response('project/add_question.html', args)

我的表格:

class QuestionTextForm(forms.ModelForm):

class Meta:
    model = Question_Text
    fields = ('text_en',)

如果有任何帮助,我将不胜感激。

1 个答案:

答案 0 :(得分:0)

您要在q之前保存c。但由于q具有c的字段(外键),因此需要首先保存c。 Django在内部引用c的id来适当地更新表和行。

所以将代码更改为

    c = f.save(commit=False)
    #          c.pub_date = timezone.now()
    c.save() #save c

    #prepare object
    q = Question()
    q.question_text = c
    q.project = a
    q.user = request.user
    q.save()