Django - 查询从其他模型中检索pk

时间:2015-06-26 17:14:59

标签: python django django-models

我正在尝试创建一个查询来从数据库中获取当前帖子的pk。然后将其设置为新帖子的外键。我正在使用formview,我试图从中检索'id'的模型叫做Projects。 Id是模型Projects的主键。

我怎么能这样做?

pk = 5,因为我不知道如何获得当前的。

views.py

class ProjectDetailToDoForm(FormView):
    model = ProjectsToDo
    form_class = ProjectToDoForm
    success_url = '../..'

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(ProjectDetailToDoForm, self).dispatch(request, *args, **kwargs)

    def form_valid(self,form):
        self.object = form.save(commit=False)
        self.object.project = Projects.objects.get(pk=5)
        self.object.save()

        return super(ProjectDetailToDoForm, self).form_valid(form)

class ProjectDetail(generic.DetailView):
    model = Projects
    context_object_name = 'indprojects'
    template_name = 'projectpage.html'

    def get_context_data(self, *args, **kwargs):
        context = super(ProjectDetail, self).get_context_data(*args, **kwargs)
        context['todolist'] = ProjectsToDo.objects.order_by('project_tododate')
        context['todoform'] = ProjectToDoForm()
        context['form'] = ProjectForm(instance=Projects.objects.get(slug=self.kwargs['slug']))
        return context

    def get_queryset(self):
        return Projects.objects.filter(user=self.request.user)

    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(ProjectDetail, self).dispatch(request, *args, **kwargs)

models.py

class Projects(models.Model):
    user = models.ForeignKey(User)
    slug = models.SlugField()
    project_title = models.CharField(max_length=30)
    project_shortdesc = models.CharField(max_length=248)
    project_desc = models.TextField()

    def save(self):
        super(Projects, self).save()
        date = datetime.date.today()
        self.slug = '%i%i%i%s' % (
            date.year, date.month, date.day, slugify(self.project_title)
        )
        super(Projects, self).save()


class ProjectsToDo(models.Model):
    project_tododate = models.DateField()
    project_tododesc = models.TextField(max_length = 500)
    project = models.ForeignKey(Projects)

    def __unicode__(self):
            return '%s %s' % (self.project_tododesc, self.project_tododate)

1 个答案:

答案 0 :(得分:2)

我猜您使用网址定义了活动项目。在这种情况下,你可以这样做:

urls.py

url(r'^(?P<project_slug>[\w-]+)/add_todo/$', 
    views.ProjectDetailToDoForm.as_view(),
    name='add_todo',
),
...

视图

def form_valid(self, form):
    self.object = form.save(commit=False)
    project = Project.objects.get(slug=self.kwargs["project_slug"])
    self.object.project = project
    self.object.save()

    return super(ProjectDetailToDoForm, self).form_valid(form)