Created
December 10, 2016 19:40
-
-
Save shlaikov/4f84df6c0f2bd501bb52d82c42439eaa to your computer and use it in GitHub Desktop.
Django model. Live search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
from django.db.models import Q | |
from django.http import HttpResponse | |
from django.shortcuts import render_to_response | |
from django.template import RequestContext | |
from django.template.loader import render_to_string | |
import json | |
class Product(models.Model): | |
categories = models.ManyToManyField(Category, | |
related_name='products', | |
blank=True, verbose_name=u"категории") | |
related_products = models.ManyToManyField('Product', | |
blank=True, | |
verbose_name="связанные продукты") | |
sku = models.CharField(u'артикул', max_length=128, validators=[validators.check_bad_symbols], unique=True) | |
price = models.DecimalField(u'цена', max_digits=12, decimal_places=4) | |
slug = models.SlugField(u'slug', max_length=80, db_index=True, unique=True) | |
name = models.CharField(u'название', max_length=128) | |
title = models.CharField(u'заголовок страницы (<title>)', max_length=256, blank=True) | |
description = models.TextField(u'описание', blank=True) | |
def live_search(request, template_name="shop/livesearch_results.html"): | |
q = request.GET.get("q", "") | |
if q == "": | |
result = json.dumps({ | |
"state": "failure", | |
}) | |
else: | |
query = Q(active=True) & get_query(q, ['name', 'description']) | |
temp = Product.objects.filter(query) | |
total = temp.count() | |
products = temp[0:5] | |
products = render_to_string(template_name, RequestContext(request, { | |
"products": products, | |
"q": q, | |
"total": total, | |
})) | |
result = json.dumps({ | |
"state": "success", | |
"products": products, | |
}) | |
return HttpResponse(result, content_type='application/json') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment