Search from two models with Haystack - django

How to have Haystack search from two models?
class People(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
def __unicode__(self):
return self.name
class Note(models.Model):
user = models.ForeignKey(CustomUser)
title = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField()
def __unicode__(self):
return self.title
Implementing two indexes did not help.

If you have registered search index for all models you can specify which of it to search e.g.:
SearchQuerySet().filter(content='foo').models(People, Note)
if not specified it will search everywhere
Indexes should be like
class PeopleIndex(indexes.SearchIndex, indexes.Indexable):
....
class NoteIndex(indexes.SearchIndex, indexes.Indexable):
....
in appropriate search_indexes.py in apps
P.S. make sure all models is indexed by doing direct queries to search engine you using (if possible)

Related

What type of database field for a multiple choice Search filter with DRF?

What type of Database field is the most efficent one for a drf based search filter? I'm trying to build a search feature where i can search by a specific set of features. You could compare it to an hotel search were you filter by Amenities that you want.
Are many to many fields the best choice for this?
I would suggest many to many fields:
from django.db import models
class Category(models.Model):
title = models.CharField(max_length=30)
def __str__(self):
return self.title
class Article(models.Model):
name = models.CharField(max_length=100)
categories = models.ManyToManyField(Category)
class Meta:
ordering = ['name']
def __str__(self):
return self.name

Syntax to reverse-query a cached queryset

I have the following 3 models related by Foreign Key as following:
class Seller(models.Model):
name = models.CharField(max_length=20)
def __str__(self):
return self.name
class Genre(models.Model):
seller= models.ForeignKey(Seller, related_name="genre", on_delete=models.CASCADE)
name = models.CharField(max_length=20)
def __str__(self):
return self.name
class Book(models.Model):
genre= models.ForeignKey(Genre, related_name="book", on_delete=models.CASCADE)
name = models.CharField(max_length=20)
def __str__(self):
return self.name
And I want to retrieve the whole 3 tables in one database query, by querying the Seller objects, as following:
sellers = Seller.objects.select_related('genre', 'book').all().values('name')
seller_df = pd.DataFrame(list(sellers))
What is the syntax to filter for books carried by a particular seller, without hitting the database again (by utilizing either the Seller queryset or the pandas seller_df)
seller1 = seller_df ['name'].iloc[0]
seller1_books = Book.objects.filter(...)
seller_last = seller_df ['name'].iloc[-1]
seller_last_books = Book.objects.filter(...)
I dont know so mach about caching but I know something that you like:
We use select_related when the object is single like onetoone or fk.
.
for many to many or reverse fk like your example use prefetch_related

Django order many to many relationship

I have been playing around with Django's many to many field with the following models:
class ProjectLanguage(models.Model):
title = models.CharField(max_length=15)
def __str__(self):
return self.title
class Project(models.Model):
title = models.CharField(max_length=30)
img = models.CharField(max_length=50)
main_text = models.TextField(default="main project description ...", null=True, blank=True)
languages = models.ManyToManyField(ProjectLanguage)
def __str__(self):
return self.title
I want to get a list of projects ordered by their ProjectLanguage title. How do I achieve this with Django ?
Thanks
Mark
You can define a method like this:
class Project(models.Model):
...
def ordered_languages(self):
return self.languages.all().order_by('title')
Or you may want to use a through table with ordering.

django admin ordering not working

in this as you can saw we change order 1, and order 0
while running it still the same
you can saw
using the shell
title at top and Whats the deal with strings?
while this has to be reverse according to the order`
Courses/model.py
from django.db import models
# Create your models here.
class Course(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=255)
description = models.TextField()
def __str__(self):
return self.title
class Step(models.Model):
title = models.CharField(max_length=255)
description = models.TextField()
order = models.IntegerField(default=0)
course = models.ForeignKey(Course)
class Meta:
ordering = ['order', ]
You have an indentation error. The Meta class for Step, which contains the ordering directive, is not actually inside the Step class. It needs to be indented one level.

Django Rest Framework Generic Relation to search by risk tag

Here are the models I created:
So I have labelled each data item (search result) with risk and now I would like to browse data item by risk within a project.
I don't have concrete idea how generic relation works. Looking up on forums I saw people using generic to have tags to results. I am using Django 1.7. I have everything working as of now, but I am not sure how to write the viewset to have search the search result by risk and so that I can query the API from front-end.
A search result can have multiple risk tagged to it
`
Risks/models.py
class Risk(models.Model):
"""Risk for data. Every risk has unique name.
"""
name = models.CharField(max_length=100, unique=True)
search_string = models.TextField(blank=True) # search keywords related to this risk
def __unicode__(self):
return 'Risk[id: {id}, name: {name}]'.format(
id=self.id, name=self.name)
class RiskItem(models.Model):
#RiskItem(content_type=article, risk=r)
risk = models.ForeignKey(Risk)
project = models.ForeignKey('engagement.Project')
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
def __unicode__(self):
return "%s :" % (self.risk.name)
I have referred to risk in the search result model by GenericRelation, by taking reference from forums. Here is how it looks like.
Here is how my search result is like and each search item is associated with a risk.
Search/models.py
from engagement.models import Project
from risk.models import RiskItem
from django.contrib.auth.models import User
class Search(models.Model):
project = models.ForeignKey(Project, related_name="searches")
user = models.ForeignKey(User)
string = models.CharField(max_length=1024) # search string
created_at = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.string
class SearchResult(models.Model):
search = models.ForeignKey(Search, related_name="results")
title = models.CharField(max_length=255)
url = models.URLField(blank=False, max_length=300)
snippet = models.TextField(blank=True)
risks = GenericRelation(RiskItem)
label = models.CharField(max_length=100, default=0)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('rank',)
def __unicode__(self):
return self.title
`
Want to create a view which list all search results by Risk, by connecting the two apis, single risk can be associated with multiple search result items.