class ResourceIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.NgramField(document=True, use_template=True) name = indexes.CharField(model_attr='name') created = indexes.DateTimeField(model_attr="created") type = indexes.MultiValueField(faceted=True) score = indexes.DecimalField(model_attr="rating") categories = indexes.MultiValueField(faceted=True) cities = indexes.MultiValueField(faceted=True) counties = indexes.MultiValueField(faceted=True) def get_model(self): return Resource def index_queryset(self, using=None): return self.get_model().objects.all() def prepare_score(self, obj): return obj.rating_score def prepare_categories(self, obj): return [category.name for category in obj.categories.all()] def prepare_cities(self, obj): return [city.name for city in obj.cities.all()] def prepare_counties(self, obj): return [county.name for county in obj.counties.all()] def prepare_type(self, obj): return [url.url_type for url in obj.url_set.all()]
class BookIndex(indexes.SearchIndex, indexes.Indexable): abstract = indexes.CharField(model_attr='abstract') name = indexes.CharField(model_attr='name') text = indexes.CharField(document=True) pages = indexes.IntegerField(model_attr='pages', faceted=True) price = indexes.DecimalField(model_attr='price', faceted=True) rating = indexes.FloatField(model_attr='rating', faceted=True) book_id = indexes.CharField(model_attr='id', faceted=False) pubdate = indexes.DateField(model_attr='pubdate', faceted=True) category = indexes.CharField(model_attr='category', faceted=True) publisher = indexes.CharField(model_attr='publisher', faceted=True) pub_year = indexes.CharField(faceted=True) def get_model(self): return Book def index_queryset(self, using=None): return self.get_model().objects.all() def prepare_author_set(self, obj): return [author.name for author in obj.authors.all().order_by('-name')] def prepare_pub_year(self, obj): return obj.pubdate.year def prepare_text(self, obj): return u'{} {}'.format(obj.name, obj.abstract)
class SKUIndex(indexes.SearchIndex, indexes.Indexable): # document = True 每个searchindex需要有一个(也是唯一一个)字段 #document = True这像Haystack和搜索引擎指示哪个字段是在其中搜索的主要字段 #text 类似于新华字典的按照笔画或者按照拼音找到对应的页数 # use_template = True 必须指定这一东西 # # 我们需要指定一个模板 来规定 模型中的哪些字段可以作为 全文索引的字段 # 模板路径必须满足 templates 下创建 search/indexes/应用名/应用名_text.txt #这允许我们使用数据模板(而不是容易出错的串联)来构建搜索引擎将索引的文档。 # 您需要在调用的模板目录中创建一个新模板 text = indexes.CharField(document=True, use_template=True) #以下字段用于数据展示 注意与model中一样 id = indexes.IntegerField(model_attr='id') name = indexes.CharField(model_attr='name') price = indexes.DecimalField(model_attr='price') default_image_url = indexes.CharField(model_attr='default_image_url') comments = indexes.IntegerField(model_attr='comments') def get_model(self): """返回建立索引的模型类""" return SKU def index_queryset(self, using=None): """返回要建立索引的数据查询集""" return self.get_model().objects.filter(is_launched=True)
class SKUIndex(indexes.SearchIndex, indexes.Indexable): """ sku索引数据模型类,作用: 1,明确搜索引擎中索引数据包含的字段,即是通过那些字段的数据来检索 2,在前端查询的关键词即是索引类中的字段名 继承: 使用haystack中的indexes提供的模型和字段 Indexable声明可以被索引 """ # document=True指明:关键字查询的字段,该字段的索引值可以由多个数据库模型类字段组成; # use_template=True指明:哪些模型类字段,后续通过模板来指明 text = indexes.CharField(document=True, use_template=True) # :默认查找路径:templates/search/indexes/goods/sku_text.txt # 其他字段通过model_attr指明:引用数据库模型类的特定字段,用于返回给前端 id = indexes.IntegerField(model_attr="id") name = indexes.CharField(model_attr="name") price = indexes.DecimalField(model_attr="price") default_image_url = indexes.CharField(model_attr="default_image_url") comments = indexes.IntegerField(model_attr="comments") def get_model(self): """ 返回建立索引的模型类:则在模板中使用的就是这个模型类的数据 """ return SKU def index_queryset(self, using=None): """ :param using: 返回建立索引的数据查询集 """ return self.get_model().objects.filter(is_launched=True)
class UserIndex(indexes.ModelSearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) skills = indexes.MultiValueField(boost=2) roles = indexes.MultiValueField(boost=2) photo = indexes.CharField() job_descriptions = indexes.MultiValueField() job_titles = indexes.MultiValueField() profile_id = indexes.IntegerField() examples = indexes.IntegerField() grade = indexes.DecimalField() def prepare(self, obj): self.prepared_data = super(UserIndex, self).prepare(obj) jobs = obj.employee_set.all() self.prepared_data['job_descriptions'] = [job.description for job in jobs] self.prepared_data['job_titles'] = [job.title for job in jobs] self.prepared_data['skills'] = [skill.name for skill in obj.skills.all()] self.prepared_data['roles'] = [role.display_name for role in obj.roles.all()] self.prepared_data['photo'] = obj.get_photo self.prepared_data['profile_id'] = obj.pk self.prepared_data['grade'] = obj.score self.prepared_data['examples'] = len(obj.work_examples.all()) return self.prepared_data def index_queryset(self, using=None): return Profile.objects.filter(tos=True, is_active=True, email_confirmed=True, score__gte=70).exclude(roles=None).exclude(long_description=None).exclude(skills=None) class Meta: model = Profile fields = ("profile_id", "first_name", "last_name", "email", "location", "photo", "roles", "skills", "email_notifications", "city", "state", "country", "grade", "long_description", "job_descriptions", "job_titles", "featured", "text", "examples", )
class AdIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) title = indexes.CharField(model_attr='title', boost=1.125) description = indexes.CharField(model_attr='description') price = indexes.DecimalField(model_attr='price') province = indexes.CharField(model_attr='province__name', boost=1.120) municipality = indexes.CharField(model_attr='municipality__name') updated_at = indexes.DateTimeField(model_attr='updated_at', use_template=False, indexed=False) # suggestions = indexes.FacetCharField() def get_model(self): return Ad def prepare(self, object): """ Its super important to avoid to reach a negative number in the boost, with a negative number the ranking will be reversed. """ self.prepared_data = super(AdIndex, self).prepare(object) self.prepared_data['_boost'] = 1 - self.compute_antiquity_penalty( self.prepared_data['updated_at']) return self.prepared_data def compute_antiquity_penalty(self, updated_at): """ Computes a increasing function given the difference of days between the current date and the updated_at. This function never reaches to 1, avoiding this way negatives numbers in document boost. """ diff = datetime.now(timezone.utc) - updated_at return 1 - 1 / (1.001**diff.days)
class WhooshRoundTripSearchIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, default="") name = indexes.CharField() is_active = indexes.BooleanField() post_count = indexes.IntegerField() average_rating = indexes.FloatField() price = indexes.DecimalField() pub_date = indexes.DateField() created = indexes.DateTimeField() tags = indexes.MultiValueField() sites = indexes.MultiValueField() # For a regression involving lists with nothing in them. empty_list = indexes.MultiValueField() def get_model(self): return MockModel def prepare(self, obj): prepped = super().prepare(obj) prepped.update( { "text": "This is some example text.", "name": "Mister Pants", "is_active": True, "post_count": 25, "average_rating": 3.6, "price": Decimal("24.99"), "pub_date": date(2009, 11, 21), "created": datetime(2009, 11, 21, 21, 31, 00), "tags": ["staff", "outdoor", "activist", "scientist"], "sites": [3, 5, 1], "empty_list": [], } ) return prepped
class SKUIndex(indexes.SearchIndex, indexes.Indexable): # 作用 # 1. 明确在搜索引擎中索引数据包含哪些字段 # 2. 字段也会作为前端进行检索查询时关键词的参数名 text = indexes.CharField(document=True, use_template=True) id = indexes.IntegerField(model_attr='id') name = indexes.CharField(model_attr='name') price = indexes.DecimalField(model_attr='price') default_image_url = indexes.CharField(model_attr='default_image_url') comments = indexes.IntegerField(model_attr='comments') def get_model(self): # 指明使用的数据库 return SKU def index_queryset(self, using=None): # 指明数据库数据建立索引的范围 # return SKU.objects.filter(is_launched=True) return self.get_model().objects.filter(is_launched=True) # ?text=iphone # ?id= # ?name=
class SKUIndex(indexes.SearchIndex, indexes.Indexable): #document=True #text 相当于我们新华字段的 汉语拼音查询 根据偏旁部首获取指定页数 #需要有一个(也是唯一一个)字段 document=True。 # 这向Haystack和搜索引擎指示哪个字段是在其中搜索的主要字段 #use_template=True # 可以使用模板来定义全文检索的字段 text = indexes.CharField(document=True, use_template=True) #制定字段 id = indexes.IntegerField(model_attr='id') name = indexes.CharField(model_attr='name') price = indexes.DecimalField(model_attr='price') default_image_url = indexes.CharField(model_attr='default_image_url') comments = indexes.IntegerField(model_attr='comments') def get_model(self): """返回建立索引的模型类""" return SKU def index_queryset(self, using=None): """返回要建立索引的数据查询集""" return self.get_model().objects.filter(is_launched=True)
class SKUIndex(indexes.SearchIndex,indexes.Indexable): '''商品索引类''' # 组合字段(id name caption: 商品副标题) # text: 名字固定 text = indexes.CharField(document=True, use_template=True) #单一字段 id = indexes.IntegerField(model_attr='id') name = indexes.CharField(model_attr='name') price = indexes.DecimalField(model_attr='price') default_image_url = indexes.CharField(model_attr='default_image_url') #评论数量 comments = indexes.IntegerField(model_attr='comments') def get_model(self): #针对商品表生成索引库 return SKU def index_queryset(self, using=None): """需要根据数据库表的哪些数据来创建索引""" # return self.get_model().objects.filter(is_launched=True) return SKU.objects.filter(is_launched=True) # 针对上架的商品创建索引
class WhooshRoundTripSearchIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, default='') name = indexes.CharField() is_active = indexes.BooleanField() post_count = indexes.IntegerField() average_rating = indexes.FloatField() price = indexes.DecimalField() pub_date = indexes.DateField() created = indexes.DateTimeField() tags = indexes.MultiValueField() sites = indexes.MultiValueField() # For a regression involving lists with nothing in them. empty_list = indexes.MultiValueField() def get_model(self): return MockModel def prepare(self, obj): prepped = super(WhooshRoundTripSearchIndex, self).prepare(obj) prepped.update({ 'text': 'This is some example text.', 'name': 'Mister Pants', 'is_active': True, 'post_count': 25, 'average_rating': 3.6, 'price': Decimal('24.99'), 'pub_date': date(2009, 11, 21), 'created': datetime(2009, 11, 21, 21, 31, 00), 'tags': ['staff', 'outdoor', 'activist', 'scientist'], 'sites': [3, 5, 1], 'empty_list': [], }) return prepped
class VerifiedUserAccountsIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True) username = indexes.CharField() email = indexes.CharField(model_attr='email') network = indexes.CharField(model_attr='network') account_id = indexes.IntegerField(model_attr='account_id') price = indexes.DecimalField(model_attr='price') cpm = indexes.FloatField(model_attr='cpm') followers = indexes.IntegerField() verified = indexes.IntegerField() iid = indexes.IntegerField() engagement = indexes.FloatField() def get_model(self): return VerifiedUserAccounts def prepare_text(self, obj): return [niche.niche for niche in obj.niches.all()] def prepare_followers(self, obj): try: if obj.network == 'ig': ig_user = IgUsers.objects.filter(id=obj.account_id) if ig_user.exists(): return ig_user.first().followers elif obj.network == 'tw': tw_user = TwUsers.objects.filter(id=obj.account_id) if tw_user.exists(): return tw_user.first().followers except Exception as e: return -1 def prepare_verified(self, obj): return 1 def prepare_iid(self, obj): return obj.account_id def prepare_username(self, obj): try: if obj.network == 'ig': ig_user = IgUsers.objects.filter(id=obj.account_id) if ig_user.exists(): return ig_user.first().username elif obj.network == 'tw': tw_user = TwUsers.objects.filter(id=obj.account_id) if tw_user.exists(): return tw_user.first().username except Exception as e: print e return None def prepare_engagement(self, obj): return calculate_engagement_stats_for_verified_users(obj)
class BovespaAccountIndex(BaseSearchIndex, indexes.Indexable): ccvm = indexes.CharField( model_attr="ccvm", faceted=True) # The date of the data for the company period = indexes.DateField( model_attr="period", faceted=True) number = indexes.CharField( model_attr="number", faceted=True) financial_info_type = indexes.CharField( model_attr="financial_info_type", faceted=True) balance_type = indexes.CharField( model_attr="balance_type", faceted=True) name = indexes.CharField( model_attr="name", faceted=True) value = indexes.DecimalField( model_attr="value") comments = indexes.CharField( model_attr="comments", faceted=True) # When was created the entity and the last modification date created_at = indexes.DateTimeField( model_attr="created_at", faceted=True) updated_at = indexes.DateTimeField( model_attr="updated_at", faceted=True) is_deleted = indexes.BooleanField( model_attr="is_deleted", faceted=True) deleted_reason = indexes.CharField( model_attr="deleted_reason") class Meta: text_fields = ["name", "comments", "deleted_reason"] # Once the index has been created it cannot be changed # with sync_indexes. Changes should be made by hand. index_settings = { "realtime": "true", "autoCommitTime": "100", "ramBufferSize": "2048" } def get_model(self): return BovespaAccount def index_queryset(self, using=None): return self.get_model().objects.filter( created_at__lte=timezone.now(), is_deleted=False )
class NoteIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) by_user = indexes.ForeignKey(model_attr='user') pub_date = indexes.DateTimeField(model_attr='pub_date') country = indexes.CharField(max_length=4) city_ascii = indexes.CharField(max_length=100) #accentCity# city = indexes.CharField(max_length=100) region = indexes.CharField(max_length=4) population = indexes.IntegerField(default=0) latitude = indexes.DecimalField(max_digits=10, decimal_places=6) longitude = indexes.DecimalField(max_digits=10, decimal_places=6) def get_model(self): return Note def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.filter( pub_date__lte=datetime.datetime.now())
class GoodsModelIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) price = indexes.DecimalField(model_attr='price') popular = indexes.IntegerField(model_attr='popular') def get_model(self): return GoodsModel def index_queryset(self, using=None): return self.get_model().objects.all()
class ZipCodeIndex(CelerySearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) # Shitty workaround to the content__contains problem contains = indexes.EdgeNgramField(use_template=True, template_name='search/indexes/location/zipcode_text.txt') code = indexes.DecimalField(model_attr='code') city = indexes.CharField(model_attr='city') state = indexes.CharField(model_attr='state') latitude = indexes.DecimalField(model_attr='latitude') longitude = indexes.DecimalField(model_attr='longitude') location = indexes.LocationField() def get_model(self): return ZipCode def get_updated_field(self): return 'updated' def prepare_location(self, obj): return '%s,%s' % (obj.latitude, obj.longitude)
class DiscountIndex(TendenciBaseSearchIndex): discount_code = indexes.CharField(model_attr='discount_code') start_dt = indexes.DateTimeField(model_attr='start_dt') end_dt = indexes.DateTimeField(model_attr='end_dt') never_expires = indexes.BooleanField(model_attr='never_expires') value = indexes.DecimalField(model_attr='value') cap = indexes.IntegerField(model_attr='cap') num_of_uses = indexes.IntegerField() def prepare_num_of_uses(self, obj): return obj.num_of_uses()
class TransferMetadataIndex(indexes.SearchIndex, indexes.Indexable): modified_datetime = indexes.DateTimeField(model_attr='modified_datetime') created_datetime = indexes.DateTimeField(model_attr='created_datetime') user_full_name = indexes.CharField(null=True) user_username = indexes.CharField(null=True) user_id = indexes.IntegerField(null=True) merchant_reference = indexes.CharField(model_attr='merchant_reference', null=True) masked_account_number = indexes.CharField( model_attr='masked_account_number') order_number = indexes.CharField(null=True) amount = indexes.DecimalField(model_attr='amount') type_code = indexes.CharField(model_attr='type_code') type_code_name = indexes.CharField(model_attr='type_name') ticket_number = indexes.CharField(model_attr='ticket_number', null=True) financing_plan_number = indexes.IntegerField(null=True) auth_number = indexes.CharField(model_attr='auth_number', null=True) status = indexes.CharField(model_attr='status') status_name = indexes.CharField(model_attr='status_name') message = indexes.CharField(model_attr='message') disclosure = indexes.CharField(model_attr='disclosure') text = indexes.EdgeNgramField( document=True, use_template=True, template_name='search/indexes/wellsfargo/transfer_text.txt') def get_model(self): return TransferMetadata def get_updated_field(self): return 'modified_datetime' def index_queryset(self, using=None): return self.get_model().objects.all() def prepare_order_number(self, obj): order = obj.get_order() return order.number if order else None def prepare_financing_plan_number(self, obj): return obj.financing_plan.plan_number if obj.financing_plan else None def prepare_user_full_name(self, obj): return obj.user.get_full_name() if obj.user else None def prepare_user_username(self, obj): return obj.user.username if obj.user else None def prepare_user_id(self, obj): return obj.user.pk if obj.user else None
class ProductsIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) name = indexes.CharField(model_attr='name') vendor_code = indexes.CharField(model_attr='vendor_code') price = indexes.DecimalField(model_attr='price') def get_model(self): return Products def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.filter(available=True)
class AdIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) title = indexes.CharField(model_attr='title') description = indexes.CharField(model_attr='description') price = indexes.DecimalField(model_attr='price') province = indexes.CharField(model_attr='province__name') municipality = indexes.CharField(model_attr='municipality__name') # suggestions = indexes.FacetCharField() def get_model(self): return Ad
class ProductIndex(indexes.SearchIndex, indexes.Indexable): # Search text text = indexes.EdgeNgramField( document=True, use_template=True, template_name='oscar/search/indexes/product/item_text.txt') upc = indexes.CharField(model_attr="upc", null=True) title = indexes.EdgeNgramField(model_attr='title', null=True) # Fields for faceting category = indexes.CharField(null=True, faceted=True) price = indexes.DecimalField(null=True, faceted=True) num_in_stock = indexes.IntegerField(null=True, faceted=True) date_created = indexes.DateTimeField(model_attr='date_created') date_updated = indexes.DateTimeField(model_attr='date_updated') def get_model(self): return get_model('catalogue', 'Product') def prepare_category(self, obj): categories = obj.categories.all() if len(categories) > 0: return categories[0].full_name def prepare_price(self, obj): # Pricing is tricky as product do not necessarily have a single price # (although that is the most common scenario). if obj.is_top_level and obj.has_stockrecords: result = strategy.fetch(obj) if result.price.is_tax_known: return result.price.incl_tax return result.price.excl_tax def prepare_num_in_stock(self, obj): if obj.has_stockrecords: result = strategy.fetch(obj) return result.stockrecord.num_in_stock def index_queryset(self, using=None): # Only index browsable products (not each individual variant) return self.get_model().browsable.order_by('-date_updated') def get_updated_field(self): """ Used to specify the field used to determine if an object has been updated Can be used to filter the query set when updating the index """ return 'date_updated'
class XapianSimpleMockIndex(indexes.SearchIndex): text = indexes.CharField(document=True) author = indexes.CharField(model_attr='author') url = indexes.CharField() non_anscii = indexes.CharField() funny_text = indexes.CharField() datetime = indexes.DateTimeField(model_attr='pub_date') date = indexes.DateField() number = indexes.IntegerField() float_number = indexes.FloatField() decimal_number = indexes.DecimalField() multi_value = indexes.MultiValueField() def get_model(self): return XapianMockModel def prepare_text(self, obj): return 'this_is_a_word inside a big text' def prepare_author(self, obj): return 'david holland' def prepare_url(self, obj): return 'http://example.com/1/' def prepare_non_anscii(self, obj): return 'thsi sdas das corrup\xe7\xe3o das' def prepare_funny_text(self, obj): return 'this-text has funny.words!!' def prepare_datetime(self, obj): return datetime.datetime(2009, 2, 25, 1, 1, 1) def prepare_date(self, obj): return datetime.date(2008, 8, 8) def prepare_number(self, obj): return 123456789 def prepare_float_number(self, obj): return 123.123456789 def prepare_decimal_number(self, obj): return '22.34' def prepare_multi_value(self, obj): return ['tag', 'tag-tag', 'tag-tag-tag']
class SubastasIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) titulo = indexes.CharField(model_attr='titulo') fechaFin = indexes.DateTimeField(model_attr='fechaFin') ofertaMax = indexes.DecimalField(model_attr='ofertaMax') detalle = indexes.CharField(model_attr='detalle') def get_model(self): return Subastas def index_queryset(self, using=None): """Queremos que se indexen todas las noticias que tengan archivada=False""" return self.get_model().objects.filter( fechaBaja=None, fechaFin__gt=datetime.datetime.now())
class SKUIndex(indexes.SearchIndex,indexes.Indexable): text = indexes.CharField(document=True, use_template=True) id = indexes.IntegerField(model_attr='id') name = indexes.CharField(model_attr='name') price = indexes.DecimalField(model_attr='price') default_image_url = indexes.CharField(model_attr='default_image_url') comments = indexes.IntegerField(model_attr='comments') def get_model(self): return SKU def index_queryset(self, using=None): return self.get_model().objects.filter(is_launched=True)
class GraspObservationConditionIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) demonstrator_species = indexes.CharField( model_attr='demonstrator_species__species_name') demonstration_type = indexes.CharField(model_attr='demonstration_type') viewing_angle = indexes.DecimalField(model_attr='viewing_angle') whole_body_visible = indexes.BooleanField(model_attr='whole_body_visible') object = indexes.CharField(model_attr='object') object_distance = indexes.DecimalField(model_attr='object_distance') grasp = indexes.CharField(model_attr='grasp') # experiment_title=indexes.CharField(model_attr='experiment__title') # experiment_brief_description=indexes.CharField(model_attr='experiment__brief_description') # collator_last_name=indexes.CharField(model_attr='experiment__collator__last_name') # collator_first_name=indexes.CharField(model_attr='experiment__collator__first_name') # collator_username=indexes.CharField(model_attr='experiment__collator__username') def get_model(self): return GraspObservationCondition def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.all()
class SKUIndex(indexes.SearchIndex, indexes.Indexable): """SKU索引数据模型类""" text = indexes.CharField(document=True, use_template=True) id = indexes.IntegerField(model_attr="id") name = indexes.CharField(model_attr="name") # price = indexes.CharField(model_attr="price") price = indexes.DecimalField(model_attr="price") default_image_url = indexes.CharField(model_attr="default_image_url") comments = indexes.IntegerField(model_attr="comments") def get_model(self): """返回建立索引的模型类""" return SKU def index_queryset(self, using=None): """返回要建立索引的数据查询集""" return self.get_model().objects.filter(is_launched=True)
class ProductIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) name = indexes.CharField(model_attr='name', boost=1.125) price = indexes.DecimalField(model_attr='price', indexed=False) category = indexes.CharField(model_attr='category', faceted=True, indexed=False) description = indexes.CharField(model_attr='description') created_at = indexes.DateTimeField(model_attr='created_at', indexed=False) name_auto = indexes.EdgeNgramField(model_attr='name') def get_model(self): return Product def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.all()
class SKUIndex(indexes.SearchIndex, indexes.Indexable): """SKU索引数据模型类,指明让搜索引擎对哪些字段建立索引""" # 字段的索引值可以由多个数据库模型类字段组成,使用模板文件来指明 text = indexes.CharField(document=True, use_template=True) # model_attr 指明引用数据库模型类的特定字段 id = indexes.IntegerField(model_attr="id") name = indexes.CharField(model_attr="name") price = indexes.DecimalField(model_attr="price") default_image_url = indexes.CharField(model_attr="default_image_url") comments = indexes.IntegerField(model_attr="comments") def get_model(self): """指明建立索引的模型类""" return SKU def index_queryset(self, using=None): """指明模型类中需要建立索引的查询集范围""" return SKU.objects.filter(is_launched=True) # 排除未上架商品
class MockAllFieldIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=False) charfield = indexes.CharField(model_attr="charfield") integerfield = indexes.IntegerField(model_attr="integerfield") floatfield = indexes.FloatField(model_attr="floatfield") decimalfield = indexes.DecimalField(model_attr="decimalfield") boolfield = indexes.BooleanField(model_attr="boolfield") datefield = indexes.DateField(model_attr="datefield") datetimefield = indexes.DateTimeField(model_attr="datetimefield") multivaluefield = indexes.MultiValueField() @staticmethod def prepare_multivaluefield(obj): return obj.charfield.split(' ', 1) def get_model(self): return MockAllField
class SKUIndex(indexes.SearchIndex, indexes.Indexable): """ SKU索引数据模型类 """ text = indexes.CharField(document=True, use_template=True) id = indexes.IntegerField(model_attr='id') name = indexes.CharField(model_attr='name') # 教程写错了,更改字段类型 与 models的SKU中保持一致 price = indexes.DecimalField(model_attr='price') default_image_url = indexes.CharField(model_attr='default_image_url') comments = indexes.IntegerField(model_attr='comments') def get_model(self): """返回建立索引的模型类""" return SKU def index_queryset(self, using=None): """返回要建立索引的数据查询集""" return self.get_model().objects.filter(is_launched=True)