问题
I was going through the django-sphinx documentation, and it looks like it allows you to filter search results using attributes,
queryset = MyModel.search.query('query')
results1 = queryset.order_by('@weight', '@id', 'my_attribute')
results2 = queryset.filter(my_attribute=5)
results3 = queryset.filter(my_other_attribute=[5, 3,4])
results4 = queryset.exclude(my_attribute=5)[0:10]
From some examples, these attributes seem to be something you specify in the sphinx configuration file, rather than being actual column values in the table. The configuration file allows something like this,
# ForeignKey's
# Apparently sql_group_column is now replaced by sql_attr_uint
sql_group_column = country_id
sql_group_column = state_id
sql_group_column = listings
# DateField's and DateTimeField's
sql_date_column = date_added
But it turns out that you can only specify Foreign Keys as this value. As illustrated in another example,
Class City(models.Model):
...
# Comment: The below should probly be country_id and state_id
country_id = models.ForeignKey(Country)
state_id = models.ForeignKey(State, blank=True, null=True)
listings = models.PositiveIntegerField(editable=False, default=0)
When the search result is printed, you get,
print results[0]._sphinx
{'id': u'5246', 'weight': 200, 'attrs': {'state_id': 3, 'country_id': 0}}
As you can see, in attrs - state_id and country_id - being FKs, show up. But listings doesn't.
And here lies my problem. If I want to filter my sphinx search results using an aribtrary column foo in my model - how would I do it?
Thanks!
Edit
In answer to Van Gale,
I'm actually using sql_attr_uint rather than sql_group_column here.. and as I mentioned in the example above.. even the example from the author of Django Sphinx (link given above) doesn't show the attribute in the _Sphinx dict if its not a FK.. (See the "As you can see" statement above). Also, I already have the SQL_Query string too.. it selects all columns in my table.. (individually, not *)
回答1:
It's been almost a year since I did a project using django-sphinx, so my memory is a bit hazy on this. But, knowing I was able to filter on normal columns, I'll just post the relevant portions of my sphinx config and maybe that will help.
sphinx.conf:
sql_query_pre =
sql_query_post =
sql_query = SELECT `id`, `content_type_id`, `site_id`, `user_id`, `title`, `abstract`, `summary`, `fulltext`, `approved` FROM `basedoc`
sql_query_info = SELECT * FROM `basedoc` WHERE `id` = $id
sql_attr_uint = content_type_id
sql_attr_uint = site_id
sql_attr_uint = user_id
sql_attr_uint = approved
As you can see, I had a non-fk column (approved) and did filter on it in the django view. So I'm guessing your problem is you need sql_attr_uint
instead of sql_group_column
, and add the sql_query
strings.
来源:https://stackoverflow.com/questions/1134691/django-sphinx-result-filtering-using-attributes