Django视图从数据库中检索对象

时间:2013-11-28 00:49:56

标签: django django-views

我在模型中有一个Product对象,

from django.db import models

class Product(models.Model):
    title = models.CharField(max_length=255, unique = True)
    description = models.TextField()
    image_url = models.URLField(verify_exists=True, max_length=200, blank = True, null = True)
    quantity = models.PositiveSmallIntegerField(default=0)

    def sell(self, save=True):
        self.quantity -= 1
        if save:
            self.save()

以及名为:product_view.html Product {{product.title}}的模板 以及名为:product_list.html {% for p in products %}{{p.id}},{% endfor %}

的模板

我想让视图从数据库中检索Product对象,使用它来呈现模板,最后返回包含结果字符串的HttpResponse对象。如果找不到具有给定product_id的Product引发404异常(或返回HttpResponseNotFound)

def productview(request, product_id):
  """
  I dont know how to write here
  """
  #render template "product_view.html" with param product
  return HttpResponse("product %s" % product_id)

同时,如果我想呈现一个包含所有可用产品列表的页面。如果产品的数量大于0,则该产品可用。模板product_list.html期望上下文中的单个参数产品引用可迭代的Product对象。

那么如何让视图检索可用的产品以及如何使用它们来呈现模板并返回包含结果字符串的HttpResponse对象?

def available_products(request):
    """
    I dont know how to write here
    """
    #render template "product_list.html" with param products
    return HttpResponse("View not implemented!")

非常感谢

2 个答案:

答案 0 :(得分:0)

你试过generic views吗?

class ProductDetailView(DetailView):
    model = Product
    template_name = 'product_view.html'


class ProductListView(ListView):
    model = Product
    template_name = 'product_list.html'

    def get_queryset(self):
        """
        Here you can filter the product list
        """
        query_set = super(ProductListView, self).get_queryset()
        return query_set.filter(quantity__gt=0)

答案 1 :(得分:0)

#views.py
from django.shortcuts import render_to_response
from .models import Product 

def productview(request):
    """
    Retrive all products
    """
    products = Product.objects.all() 
    return render_to_response('product_list.html',{'products': products})

def available_products(request):
    """
    Retrive available products
    """
    products = Product.objects.filter(quantity__gt=0) 
    return render_to_response('product_list.html',{'products': products})

这两个也可以在一个视图中组合,具体取决于定义的url模式。 例如:

#urls.py
urlpatterns = patterns('',

    url(r'^product/(?P<which>\w+)/$', 'app_label.views.product_view'),
)

#views.py
def product_view(request, which):
    """
    Retrive available products
    """
    if which == 'all':
        products = Product.objects.all() 
    else:
        products = Product.objects.filter(quantity__gt=0) 
    return render_to_response('product_list.html',{'products': products})