Serializing enum fields spring data solr - solrj

I have this field in my domain object
#Field
#Enumerated(EnumType.STRING)
private SectionType sectionType;
but when I check the value stored in Solr it is something like:
com.x.y.objects.SectionType:H_HPI
What I want is just H_HPI or it is as if I'm calling specialty.name() method
Also I want a serializer that does that for all the enum fields in my domain objects.
I know that for neo4j, for instance, has such a serializer and can be supplied to the field as an annotation. Also mongodb does the conversion automatically.

I had same problem and found this from Spring Data Solr codes
else if (fieldValue instanceof Enum) {
field.setValue(this.getConversionService().convert(fieldValue, String.class), 1f);
}
it sets the String value
https://github.com/spring-projects/spring-data-solr/commit/4bf0af3344ec9e92ac241eaa25883e73b08f3b0b

Related

Which method of 'Django Serializer' do I need to customize?

The frontend sends the json in an array.
I received the value with difficulty as shown in ex) below.
ex)
applier_phone = data.get('phone')[0]
applier_name = data.get('name')[0]
applier_birth = data.get('birth')[0]
applier_gender = data.get('gender')[0]
But I want to get the value using Serializer.
In this case, which method of Serializer do I need to customize?
I don't think the best solution would be to modify the Serializer in itself. Rather i would suggest to modify the Json Object so the serializer detects it as by the initial schema od your Model.
This will let the Serializer still be usable for multiple case and instances.
If you still want to take the first approach i would suggest you may intervene in any of the .create() .update() , or even validate() methods for re-structuring your JSON object.

Flask-WTF default for a SelectField doesn't work for SQLAlchemy enum types

I have a Flask-SQLAlchemy site which uses the SQLAlchemy enum type for certain columns, to restrict possible input values.
For example, I have a "payment type" enum that has a few payment type options, like so:
class PaymentType(enum.Enum):
fixed = "fixed"
variable = "fixed_delivery"
quantity_discount = "quantity_discount"
When I use this in a dropdown/select I can specify the options like so:
prd_payment_type = SelectField(_('prd_payment_type'), choices=SelectOptions.PaymentTypes.All(0, _('PleaseSelect')))
The All() function I'm calling returns the different enum values as options, and also adds a custom "Please select..." option to the dropdown list. It looks like this:
class PaymentTypes(object):
#staticmethod
def All(blank_value=None, blank_text=None):
ret = [(i.value, _(i.name)) for i in PaymentType]
SelectOption.add_blank_item(ret, blank_value, blank_text)
return ret
So far, so good, I get a nice dropdown, with the correct options. the problem arises when I want to display the form using an already existing SQLAlchemy object from the database.
When I fetch the object from SQLAlchemy, the prd_payment_type property contains the enum PaymentType.quantity_discount, not just a string value 'quantity_discount':
Because WTForms (presumably) matches the pre-selected option in the dropdown to a string value "quantity_discount", it doesn't match the enum in the SQLAlchemy model and the option is not selected in the dropdown.
The SelectField of WTForms accepts a list of tuples containing strings as choices. I can't feed it my enum.
On the other hand, the SQLAlchemy model returns an enum type as the property for prd_payment_type. I could maybe override this property or something, but that feels like a lot of work to support SQLAlchemy's enums in WTForms.
Is there a standard solution for working with SQLAlchemy's enums in a WTForms SelectField or should I abandon using enums altogether and just store strings, maybe from a list of constants to keep them in check?
I have found a solution myself. It seems that when the enum has a
def __str__(self):
return str(self.value)
That's enough for WTForms to match the database value to the SelectField value.
I have made a baseclass that derives from enum.Enum and added the code above to return the enum value as a string representation.
This solution was based on these similar problems I found later on:
https://github.com/flask-admin/flask-admin/issues/1315
Python Flask WTForm SelectField with Enum values 'Not a valid choice' upon validation

How can I set the value of objectID in algolia rails?

I am using algolia gem in my rails app. I am currently combining 3 different models into one index for a combined search of our case studies, blog posts and videos.
I am having trouble as indexing one model will overwrite objects from another model as Algolia appears to use the rails generated ID to map to objectID column.
posts.rb
algoliasearch auto_index: false, if: :open?, index_name: "combined_#{Rails.env}" do
attribute :objectID do
"p#{id}"
end
end
video.rb and case_studies.rb
In the same fashion I try to set attribute :objectID to "v#{id}" for videos as well as set attribute :objectID to "c#{id}" for case studies
This virtual attribute style did not work, so I attempted to create an actual string column on the db and reindex that way to no avail.
If anyone have any ideas here I would really appreciate it and I am running low.
You can use the custom ObjectID inside each of your Model.
Inside your model
def custom_algolia_id
"v#{id}"
end
algoliasearch id: :custom_algolia_id do
attribute :title, :length
end

Django tastypie, possible to return only metadata for a query

I have a Django Tastypie API set up.
I would like to query the database for the count of objects that match a name.
Is this possible on an existing model resource, or do I need to set up a new resource to handle this specific case? (This data is usually returned in the metadata part of the result? Is there an option just to return that from the paramaters?)
So if my url is usually like this:
http://127.0.0.1:8000/api/v1/library/?name__icontains=ABC
Can I add a parameter or change the url so that it only returns the metadata (I only want the number of libraries returned that have a name containing "ABC") rather than all the objects?
You can pass in a get param:
http://127.0.0.1:8000/api/v1/library/?name__icontains=ABC&meta_only=true
and add this method to your resource:
def alter_list_data_to_serialize(self, request, data):
if request.GET.get('meta_only'):
return {'meta': data['meta']}
return data
documentation : http://django-tastypie.readthedocs.org/en/latest/resources.html#alter-list-data-to-serialize

Converting JSON to model instance in Django

What's the best way in django to update a model instance given a json representation of that model instance.
Is using deserialize the correct approach? Are there tutorials available out there?
The best approach would be to utilize one of the existing Django applications that support serializing model instances to and from JSON.
In either case, if you parse the JSON object to a Python dictionary, you can basically use the QuerySet.update() method directly.
So, say you get a dictionary where all the keys map to model attributes and they represent the values you'd want to update, you could do this:
updates = { # Our parsed JSON data
'pk': 1337,
'foo': 'bar',
'baz': 192.05
}
id = updates.pop('pk') # Extract the instance's ID
Foo.objects.filter(id=id).update(**updates) # Update the instance's data