-1

在views.py里面我有这个:

def confirm(request):
    item = PurchaseOrder.item_number  # I want to have the primary key in here and this is wrong 
    return HttpResponse('test successful')

在models.py里面我有这个:

from django.db import models

class PurchaseOrder(models.Model):
    item_number = models.AutoField(primary_key=True)

我怎样才能做到这一点,以便该项目将调用 PurchaseOrder 的主键?我必须从models.py 导入文件吗?我很抱歉,我对 Django 很陌生,在这方面找不到任何东西。

4

2 回答 2

1

本教程的第 3 部分介绍了这一点,但您需要查找:

from django.shortcuts import get_object_or_404
from myapp.models import PurchaseOrder

def confirm(request, itemnum):
    item = get_object_or_404(PurchaseOrder, item_number=itemnum)
    print("Got item #: {0.item_number}".format(item)) # a test
    return HttpResponse('test successful')

然后在你的urls.py

from django.conf.urls import patterns, url
from myapp import views

urlpatterns = patterns('',
    # your other normal url patterns
    url(r'^(?P<itemnum>\d+)/$', views.confirm, name='confirm-page'),
)
于 2013-07-29T19:24:39.610 回答
0

是的,您需要将模型导入视图。

from myappname.models import PurchaseOrder

def confirm(request):
  items = PurchaseOrder.objects.all()
  return HttpResponse(' '.join([i.item_number for i in items]))

我建议您阅读教程:
https
://docs.djangoproject.com/en/dev/intro/tutorial01/ 它解释了如何使用模型。

于 2013-07-29T19:24:28.200 回答