Filter products by attribute
I'm working on an eshop with Satchmo framework. Does 开发者_开发知识库anyone know what steps should i follow in order to filter products according to a custom attribute(type of material) in order to present the products that have the same kind of material in a page(material.html)? Should i make a material_view function Should i override get_absolute_url function?
If you want to do this without touching the core code, I would make a local app localsite/product and in models.py:
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")
Add this new app to your admin, and to additionally make them available from the product page, add them as inline:
# 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)
Then you can adapt your views/urls:
# 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))
When you say "custom attribute" do you mean that you have modified the product.models.Product
code to add another field?
If that is the case you'll probably want to create a custom view.
If your Product code is something like...
class Product(models.Model):
...
matieral_type = models.CharField(max_length=128)
...
...then you can build a view like this...
def material(request,material_type):
prods = Product.objects.filter(material_type=material_type)
return render_to_response('material.html',{'products',prods},RequestContext(request))
精彩评论