英文:
How to sort the products in the Django online store
问题
views.py
class SectionView(View):
def get(self, request, *args, **kwargs):
sort_form = request.GET.getlist('sort')
products = Product.objects.filter(available=True)
if sort_form.is_valid():
needed_sort = sort_form.cleaned_data.get("sort_form")
if needed_sort == "ДТ":
products = products.order_by("created") # 或者 updated 根据你定义的日期排序
elif needed_sort == "ДЕД":
products = products.order_by("price")
elif needed_sort == "ДОД":
products = products.order_by("-price")
return render(
request=request,
template_name='main/index.html',
context={
'products': products,
}
)
forms.py
class SortForm(forms.Form):
sort_form = forms.TypedChoiceField(label='排序:', choices=[('ПУ', '默认'), ('ДТ', '按日期'), ('ДЕД', '从便宜到贵'), ('ДОД', '从贵到便宜')])
index.py
<form action="{% url 'product_list' %}" method="get" class="sort-form">
{{ sort_form }}
<p><input type="submit" name="sort" value="排序"></p>
{% csrf_token %}
</form>
英文:
How to sort the goods in the online store so that you can click on the button and the sorting has changed, for example: price,-price. And to views.py was in class, not in def.
views.py
class SectionView(View):
def get(self, request, *args, **kwargs):
sort_form = request.GET.getlist('sort')
products = Product.objects.filter(available=True)
if sort_form.is_valid():
needed_sort = sort_form.cleaned_data.get("sort_form")
if needed_sort == "ДТ":
products = products.order_by(
"created") # или updated в зависимости от того, что ты вкладываешь в понятие по дате
elif needed_sort == "ДЕД":
products = products.order_by("price")
elif needed_sort == "ДОД":
products = products.order_by("-price")
return render(
request=request,
template_name='main/index.html',
context={
'products':products,
}
)
forms.py
class SortForm(forms.Form):
sort_form = forms.TypedChoiceField(label='Сортировать:', choices=[('ПУ', 'По умолчанию'), ('ДТ', 'По дате'), ('ДЕД', 'От дешевых к дорогим'), ('ДОД', 'От дорогих к дешевым')])
index.py
<form action="{% url 'product_list' %}" method="get" class="sort-form">
{{ sort_form }}
<p><input type="submit" name="sort" value="Сортировать"></p>
{% csrf_token %}
</form>
答案1
得分: 0
以下是翻译好的代码部分:
# 一个示例,你可以如何处理它:
class SortProduct:
def __init__(self, products):
products = products
def sort_by_price(self, descending=False):
if descending:
self.products = self.products.order_by('-price')
else:
self.products = self.products.order_by('price')
def sort_by_popularity(self, descending=False):
if descending:
self.products = self.products.order_by('-popularity')
else:
self.products = self.products.order_by('popularity')
def filter_brand(self, brandname):
self.products = self.products.filter(brand=brandname)
class SectionView(View):
def get(self, request):
# 初始化类并设置产品数据
_product = SortProduct(products=products.objects.filter(somefilter=request.GET('somefilter')))
# 设置一个过滤器集
filterset = {'sort_by_price':_product.sort_by_price,
'sort_by_popularity':_product.sort_by_popularity,
'filter_brand':_product.filter_brand,
}
# 使用过滤器集进行过滤
if request.GET('sort_by_price'):
filterset[request.GET('sort_by_price')](request.GET('descending'))
if request.GET('sort_by_popularity'):
filterset[request.GET('sort_by_popularity')](request.GET('descending'))
if request.GET('filter_brand'):
filterset[request.GET('filter_brand')](request.GET('brand'))
# 以JSON格式返回过滤后的产品
return JsonResponse(list(_product.values()), safe=False)
urlpatterns = [
path('/product', SectionView.as_views(), name='sectionviews'),
]
英文:
A sample of how you could approach it:
class SortProduct:
def __init__(self, products):
products = products
def sort_by_price(self, descending=False):
if descending:
self.products = self.products.order_by('-price')
else:
self.products = self.products.order_by('price')
def sort_by_popularity(self, descending=False):
if descending:
self.products = self.products.order_by('-popularity')
else:
self.products = self.products.order_by('popularity')
def filter_brand(self, brandname):
self.products = self.products.filter(brand=brandname)
class SectionView(View):
def get(self, request):
# Intializing class and setting products data
_product = SortProduct(products=products.objects.filter(somefilter=request.GET('somefilter')))
#Setting up a filterset
filterset = {'sort_by_price':_product.sort_by_price,
'sort_by_popularity':_product.sort_by_popularity,
'filter_brand':_product.filter_brand,
}
#Filtering using a filterset
if request.GET('sort_by_price'):
filterset[request.GET('sort_by_price')](request.GET('descending'))
if request.GET('sort_by_popularity'):
filterset[request.GET('sort_by_popularity')](request.GET('descending'))
if request.GET('filter_brand'):
filterset[request.GET('filter_brand')](request.GET('brand'))
#Returning filtered products as JSON
return JsonResponse(list(_product.values()), safe=False)
urlpatterns = [
path('/product', SectionView.as_views(), name='sectionviews'),
]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论