Skip to content

Commit

Permalink
Add queryset also method - like only but additive
Browse files Browse the repository at this point in the history
  • Loading branch information
rlskoeser committed Apr 24, 2019
1 parent 9ed14ac commit feb3e9d
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
17 changes: 15 additions & 2 deletions parasolr/query/queryset.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ def query(self, **kwargs) -> 'SolrQuerySet':
qs_copy.get_results(**kwargs)
return qs_copy

def only(self, *args, **kwargs) -> 'SolrQuerySet':
def only(self, *args, replace=True, **kwargs) -> 'SolrQuerySet':
"""Use field limit option to return only the specified fields.
Optionally provide aliases for them in the return. Subsequent
calls will *replace* any previous field limits. Example::
Expand All @@ -358,12 +358,25 @@ def only(self, *args, **kwargs) -> 'SolrQuerySet':
"""
qs_copy = self._clone()
# *replace* any existing field list with the current values
qs_copy.field_list = list(args)
if replace:
qs_copy.field_list = list(args)
# unless specified, in which case append
else:
qs_copy.field_list.extend(list(args))

for key, value in kwargs.items():
qs_copy.field_list.append('%s:%s' % (key, value))

return qs_copy

def also(self, *args, **kwargs) -> 'SolrQuerySet':
"""Use field limit option to return the specified fields,
optionally provide aliases for them in the return. Works
exactly the same way as :meth:`only` except that it
does not any previously specified field limits.
"""
return self.only(*args, replace=False, **kwargs)

def highlight(self, field: str, **kwargs) -> 'SolrQuerySet':
""""Configure highlighting. Takes arbitrary Solr highlight
parameters and adds the `hl.` prefix to them. Example use::
Expand Down
24 changes: 24 additions & 0 deletions parasolr/query/tests/test_queryset.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,30 @@ def test_only(self):
fields_sqs = sqs.only(title='title_i')
assert 'title:title_i' in fields_sqs.field_list

def test_also(self):
mocksolr = Mock(spec=SolrClient)
sqs = SolrQuerySet(mocksolr)
also_fields = ['title', 'author', 'date']
# field names, single list
fields_sqs = sqs.also(*also_fields)
# field list refined
assert fields_sqs.field_list == also_fields
# original field list unchanged
assert not sqs.field_list

# chaining is equivalent, since it adds
fields_sqs = sqs.also('title').also('author').also('date')
# field list refined
assert fields_sqs.field_list == also_fields
# original field list unchanged
assert not sqs.field_list

# with field alias
fields_sqs = fields_sqs.also(title='title_i')
# still includes previous
assert 'author' in fields_sqs.field_list
assert 'title:title_i' in fields_sqs.field_list

def test_highlight(self):
mocksolr = Mock(spec=SolrClient)
sqs = SolrQuerySet(mocksolr)
Expand Down

0 comments on commit feb3e9d

Please sign in to comment.