db.expando + App Engine + Change an integer property value to float value - google-app-engine

I've following model set up initially
class Obj (db.Model):
name = db.StringProperty(required=True)
rating = db.IntegerProperty(default=0, required=False)
There are entities already created with above, such as:
name="test1", rating="3"
So, I need to change the rating type to float. I was trying to achieve this with db.Expando
class Obj (db.Expando):
name = db.StringProperty(required=True)
rating = db.FloatProperty(default=0, required=False)
Before I'm able to retrieve the instance of the Obj model to update it to float value, I've already got the following error:
Property rating must be a float
At first, I got this error, because I wasn't using db.Expando. However, after using db.Expando, I assumed this error shouldn't come into place ? Since it can dynamically change value, type etc as I read the articles.
Being new to db.Expando, I need help. Does anyone have clue to what happened ?
EDIT
for o in Obj.all():
a = []
if o.rating:
o.rating = float(str(restaurant.rating))
else:
o.rating = float(0)
a.append(restaurant)
db.put(a)
After having above code, the same error pops up
Property rating must be a float
SOLUTION
Temporarily removed the rating from model definition and updated the values to float first and then add the new rating definition with db.FloatProperty

A db.Expando model allows you to add properties that aren't defined in the class itself; however, any properties that are explicitly defined in the class do need to be the correct type.
Simply removing rating from the model definition may work for you.

Related

adding required property option not working

I'm trying to add property options to my model. I have a StringProperty and I added required=True but I'm still able to create an object with the required field being empty.
I tried it in the admin and also in my update form for the specific model so not sure what I'm doing wrong?
You can create it, but can you put it?
class x(ndb.Model):
author = ndb.StringProperty(required=True)
a = x()
a.put()
Fails with: BadValueError: Entity has uninitialized properties: **author**
Setting a value on the required property author allows you to save it:
a.author = "some_value"
The put can now succeed.
key = a.put()
and key is now:
Key('x', 5707702298738688)
or even key.urlsafe()
ahNzfnNoYXJlZC1wbGF5Z3JvdW5kcg4LEgF4GICAgICArpkKDKIBEDYwNTM4Njc2MzY2NTQwODA
Read more about storing data here.

getting Value of a field by its Name in apex salesforce

in my visualforce page i have some campaign object first user select an object then there is a multi picklist. in this picklist there is Label for all the fields user selects some fields then i have to show the value of these fields in the selected campaign object
for showing multiple picklist my apex function is
public List<SelectOption> getOptionalFields(){
Map <String, Schema.SObjectField> fieldMap= Campaign.sObjectType.getDescribe().fields.getMap();
List<SelectOption> fieldsName =new List<SelectOption>();
for(Schema.SObjectField sfield : fieldMap.Values())
{
schema.describefieldresult dfield = sfield.getDescribe();
fieldsName.add(new SelectOption(dfield.getName(),dfield.getLabel()));
}
but i have no idea how to show value for the the field
for exmple i have object instance like
Campaign c;
now i have to get value of any field whose Name is in string form.how to get corresponding value for that field.one solution is just write like
say
String fieldName;
and use multiple if
if(fieldName=='Name')
c.Name=
if(fieldName=='Id')
c.Id=
is there any other convenient method??please explain!!
You need to read about "dynamic apex". Every "concrete" sObject (like Account, Contact, custom objects) can be cast down to generic sObject (or you can use the methods directly).
Object o = c.get(fieldName);
String returnValue = String.valueOf(o);
There are some useful examples on dynamic get and set methods on Salesforce-dedicated site: https://salesforce.stackexchange.com/questions/8325/retrieving-value-using-dynamic-soql https://salesforce.stackexchange.com/questions/4193/update-a-records-using-generic-fields (second question is a bit more advanced)
You'll still need to somehow decide when to return it as String, when as number, when as date... Just experiment with it and either do some simple mapping or use describe methods to learn the actual field type...

app engine python: populate structured property with json gives error

Context
I have the following data structure:
class Birthday(ndb.Model):
day = ndb.IntegerProperty()
month = ndb.IntegerProperty()
year = ndb.IntegerProperty()
class User(ndb.Model):
name = ndb.StringProperty()
birthday = ndb.StructuredProperty(Birthday)
# ... other properties
Problem
When I try to use the populate() method on an instance of User, it gives an error: expecting a Birthday instance instead of a dictionary of params.
If I remove the birthday property, everything works fine: the User instance is populated with the dictionary of params.
Shouldn't the populate() method recognize structured properties and automatically populate them as well?
Any clues?
Thanks
PS: The populate method could also use a forgiving mode on which it ignores unknown properties for which there are references on the params dictionary.
>>Added comments
I'm using a generic REST Handler which is extended for accessing and changing several data types. The extension has to define a method getModel() that returns the model class to access/manipulate. The model class has to implement a few methods, namely create(cls, params).
The POST handler parses params (sent by AngularJS using $resouce -- link below) the following way:
# inside the generic REST Handler
params = json.loads(self.request.body, object_hook=self.datetime_decoder) # parse json params
...
self.getModel().create(params) # invokes the create method of the
The model class implements the create method the following way:
#classmethod
def create(cls, params = None):
obj = cls()
if params:
obj.update(**params)
obj.put()
return True, obj
return False, None
The contents of the JSON dict are:
{"name":"Ana Matos","email":"ana.matos#nvd.com","phone":"+35196983465671","birthday":{"day":1,"month":0,"year":1980},"gender":"FEMALE","groups":["2012/2013"],"serviceProviderId":206133}
JSON contens -- firefox screenshot
AngularJS $resource
Are you reporting a bug or requesting a feature? The populate() method requires its parameter types to match the declared type of the property, which in this case is a Birthday instance.
It would help if you showed the contents of the JSON dict that you are passing to populate() (and exactly how you are passing it).
Possibly the solution is as simple as getting the 'birthday' value from the JSON dict and using it to create a Birthday instance. But I would have to see your code to know for sure.

GQL db.Model default parameter value

I found it kinda troublesome or difficult to find exact example I wanted for GQL.
Given the following:
class Sample (db.Model):
name = db.StringProperty(required=True)
type = db.StringProperty(required=False)
How do I set default parameter value.Let's say, I want to set type parameter to the value of "new" when I do following:
Sample(name="Yeah").put()
What would be the format of setting the default parameter value for a class inherited db.Model ?
Just add "default" parameter in the definition of your type, like this:
class Test(db.Model):
Test = db.StringProperty(default="test")

what is wrong in this query

I have a table something like
class BulkStore(PresageBaseModel):
store_key = db.StringProperty(required=True)
name = db.StringProperty(required=True)
But when I query on store_key it doesn't return anything
sk = 'agd2b3hhdWxhcjcLEhZwcmVzYWdlX2FwcF9jb2xsZWN0aW9uIhtwcmVzYWdlX2RlbW9fY29sbGVjdGlvbl9rZXkM'
print BulkStore.all().filter('store_key',sk).fetch(1)
output:
[]
but manual search gets the correct result
for bulkStore in BulkStore.all():
if bulkStore.store_key == sk:
print bulkStore
output:
BulkStore(key_id=849L, store_key=u'agd2b3hhdWxhcjcLEhZwcmVzYWdlX2FwcF9jb2xsZWN0aW9uIhtwcmVzYWdlX2RlbW9fY29sbGVjdGlvbl9rZXkM', name=u'collection_record_export')
What i may be missing?
In one of your examples, the string ends with a ., in the other, it doesn't. These are not equal strings.
Reason for this bug is that if a property is assigned a value which is already another db type it mysteriously takes the type of that value, e.g. in my BulkStore model store_key is a StringProperty but if I assign it a value which is TextProperty, store_key is stored as TextProperty not StringProperty which I have defined it to be and later on query on such properties doesn't work, so in db you can have entities some of which will be searchable and some won't be.
so never do this
bulkstore.store_key = some_entity.some_text_value
instead do this
bulkstore.store_key = str(some_entity.some_text_value)
This can be a very subtle bug to find in code :(

Resources