【问题标题】:Filter products by attribute按属性过滤产品
【发布时间】:2011-06-22 15:57:14
【问题描述】:

我正在使用 Satchmo 框架开发一个 eshop。 有谁知道我应该遵循哪些步骤才能根据自定义属性(材料类型)过滤产品,以便在页面(material.html)中呈现具有相同材料类型的产品? 我应该做一个material_view函数 我应该重写 get_absolute_url 函数吗?

【问题讨论】:

    标签: django satchmo


    【解决方案1】:

    如果您想在不触及核心代码的情况下执行此操作,我会在 models.py 中创建一个本地应用程序 localsite/product:

    class Material(models.Model):
        product = models.ManyToManyField(Product, blank=True, null=True)
        name = models.CharField(_("Name"), max_length=30)
        slug = models.SlugField(_("Slug"), help_text=_("Used for URLs, auto-generated from name if blank"), blank=True, unique=True)
        description = models.TextField(_("Description"), blank=True, help_text="Optional")
    

    将此新应用添加到您的管理员中,并另外在产品页面中提供它们,将它们添加为内联:

    # if you have lots of products, use the nice horizontal filter from django's admin
    class MaterialAdmin(admin.ModelAdmin):
        filter_horizontal = ('product',)
    
    class Material_Inline(admin.TabularInline):
        model = Material.product.through
        extra = 1 
    
    admin.site.register(Material, MaterialAdmin)
    
    # Add material to the inlines (needs: from product.admin import Product, ProductOptions)
    ProductOptions.inlines.append(Material_Inline)
    admin.site.unregister(Product)
    admin.site.register(Product, ProductOptions)
    

    然后您可以调整您的视图/网址:

    # urls.py
    url(r'^material-list/([\w-]+)/$', material_list, {}, name="material_list"),
    
    # view.py
    def material_list(request, slug):
        products = Product.objects.filter(material__slug='slug')
        return render_to_response('localsite/material/list.html', {'products':products}, context_instance=RequestContext(request))
    

    【讨论】:

    • andzep 我爱你。我正陷入 satchmo 定制疯狂,但这个答案在 30 分钟内完成了!
    • 很高兴这对您有用。是的,在我在 satchmo 上的第一个项目之后,我发现,在 99.99% 的情况下,您总能找到一个不错的、小型的解决方案,而无需触及核心。但问题主要在于找到“怎么回事”:-)
    【解决方案2】:

    当您说“自定义属性”时,您的意思是您修改了product.models.Product 代码以添加另一个字段?

    如果是这种情况,您可能需要创建自定义视图。

    如果您的产品代码类似于...

    class Product(models.Model):
        ...
        matieral_type = models.CharField(max_length=128)
        ...
    

    ...那么你可以像这样构建一个视图...

    def material(request,material_type):
        prods = Product.objects.filter(material_type=material_type)
        return render_to_response('material.html',{'products',prods},RequestContext(request))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      相关资源
      最近更新 更多