Home > other >  [resolved] [DRF haystack/elasticsearch] how to create a model to store list in es?
[resolved] [DRF haystack/elasticsearch] how to create a model to store list in es?

Time:09-19

This project adopts the django framework of DRF
Because the project itself needs, now plans to News, News, etc in the es, adopts es, mysql mixed mode
Es convenient json format attracted me, so before going to the database model of
./models. Py
 
Class News (models. Model) :
"" "
News
"" "
Title=models. CharField (max_length=256, verbose_name="title")
Level=models. ForeignKey (level, verbose_name="belongs to grading," on_delete=models. SET_NULL, null=True, blank=True)
The content=models. TextField (verbose_name="content")
The author=models. ForeignKey (User, verbose_name="author", on_delete=models. SET_NULL, null=True, blank=True)
Cancomment=models. IntegerField (verbose_name="comments can be", choices=CAN_CHOICES, default=1)
Create_date=models. DateTimeField (verbose_name="creation time," auto_now_add=True)
Watch_count=models. IntegerField (verbose_name="views", the default=0)
Pass

The class NewsPicsUri (models. Model) :
"" "
News pictures attachment address
"" "
Path=models. CharField (verbose_name="news image path", max_length=255)
The parent=models. ForeignKey (News, verbose_name="belongs to the News," on_delete=models. The CASCADE)
Pass

Deposited into a similar to the following structure in the es
 
{
"Title" : "XXX",
"Content" : "XXXX",
.
"Pics" : [
{" path ":" XXXX "},
{" path ":" XXXX "},
],
.
}

In addition to create indexes for News model you need to do? The NewsPicsUri create indexes, too?
./news_index. Py
 
Class NewsIndex (indexes. SearchIndex indexes. The Indexable) :

# must field
Text=indexes. CharField (document=True, use_template=True)

Model # must return to the overloaded
Def get_model (self) :
Return News

Overloaded # must be returned by the query set
Def index_queryset (self, using=None) :
Return the self. Get_model (). Objects. All ()

Pass

CodePudding user response:

Solve,
Index class add
 pics=indexes. MultiValueField () 

The multi-value field
And then a custom function, starting with prepare_, followed by the field name
 
# custom pics field, must be the list of the JSON format
Def prepare_pics (self, obj) :
Return [{" path ": the PIC. The path} for PIC in obj. Newspicsuri_set. All (the)]


Attention should be paid to the index file called search_indexes. Py, cannot be wrong, when otherwise rebuild_index is invalid,

CodePudding user response:

Edit again...
The
 {" path ": the PIC. The path} 
the es7. X version is ok, when I am down to es2. After x version is not allowed, the pics only normal list, cannot be nested list json, so 2 x version to
 
# custom pics field, must be the list of the JSON format
Def prepare_pics (self, obj) :
[PIC. The return path for PIC in obj. Newspicsuri_set. All (the)]

In the corresponding django elasticsearch library should also be downgraded to a 2. X version
  • Related