【问题标题】:Django view retrieve the object from the databaseDjango视图从数据库中检索对象
【发布时间】:2013-11-28 00:49:55
【问题描述】:

我在模型中有一个 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 的产品,则引发 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 期望上下文中的单个参数 products 引用 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!")

非常感谢

【问题讨论】:

  • 是渲染模板还是返回字符串?
  • 有趣的是,我正在解决与您完全相同的家庭作业:) 只是应该不是“我不知道如何在这里写”,而是应该:“””编写您的视图实现以进行练习4 这里。去掉下面的当前返回行。"""

标签: django django-views


【解决方案1】:

你试过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)

【讨论】:

    【解决方案2】:
    #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})
    

    【讨论】:

      猜你喜欢
      • 2019-12-17
      • 1970-01-01
      • 2020-11-14
      • 1970-01-01
      • 2017-12-28
      • 1970-01-01
      • 2010-11-05
      • 2020-06-04
      • 2018-01-21
      相关资源
      最近更新 更多