On querying pymongo i get a dictionary object that can be sent directly as a response to the api request. Where as mongoengine returns a Document object on querying database. So I have to parse every object before it can be sent as the response in the api.
this is how I have to query in mongoengine.
users = User.objects(location = 'US')
This will return me a BaseQueryList object which contains User model type object. Instead I need that it should return me a list of dictionary type objects of Users.
In BaseQueryList there is one method called as_pymongo, we can use this to get rows as list of dict like where we get pymongo. The following is an example
users = User.objects(location = 'US').as_pymongo()
OR
In BaseQueryList there are in list of User class objects.
In User class object there is one method called _data, this will returns data as dict
So you can try like following
users = [user._data for user in users._iter_results()]
It could be help you.
Mongoengine has to_mongo() method that gives you Python dict.
users = User.objects(location = 'US')
users.to_mongo()
Related
I'm trying to pass some data about a user as JSON, and because the User object has many-to-many relationships, serializing a user as JSON seems to only include the primary key of the m-n object.
(e.g. each user has hobbies, but in the JSON it will only have the PK of the hobbies)
Anyway, I tried constructing a schema to solve this as such:
[[{user}, [hobbies]], [{user}, [hobbies]],...]
But whenever I try to serialize this (in Python it's basically an array with an object and another array in it), I get the error:
'list' object has no attribute '_meta'
Why is this happening and how can I fix it?
EDIT:
Here's the code for it:
for u in allUsers:
if searchedHobby in u.hobbies.all():
user = [u]
userHobbies = []
for hobby in u.hobbies.all():
userHobbies.append(hobby.name)
user.append(userHobbies)
response.append(user)
data = serializers.serialize('json', response)
As seen in the django github repository the serialize method expects a queryset.
What you could do is to do a json.dumps(response) and return that in the HttpResponse.
I am creating an api for some simple forum using pyramid and sqlalchemy. I have a view which I want to simply return some posts in json form to the client, when the user scrolls down to the end of the page. For some reason, the query isn't even being run and I'm being returned a query object instead of a rowproxy object. This is just a test query btw, I'm just getting a few times from the db and trying to send them in json.
#view_config(route_name='get-posts', renderer='json')
def get-posts(request)
q = session.query(Topic).filter(Topic.name =='gaming')\
.order_by(desc(Topic.topic_date)).limit(10)
results = [dict(zip(row.keys()) for row in q)]
return {'posts' : results}
When this is run, I get "AttributeError: 'Topic' object has no attribtue keys", and upon checking the type of q, I discover it is of type:sqlalchemy.orm.query.Query
Does anyone know why the query is not being run? I have a non api view function where i'm doing practically the same thing, and returning the result ( a row proxy as the contents of a dictionary and it works...
This is by design. There are methods on query that cause execution of the underlying query. all(), one(), first(), etc.
If you need the query object as list, call all() on it:
#view_config(route_name='get-posts', renderer='json')
def get-posts(request)
q = session.query(Topic).filter(Topic.name =='gaming')\
.order_by(desc(Topic.topic_date)).limit(10)
return {'posts' : q.all()}
Reference for the query object: http://docs.sqlalchemy.org/en/latest/orm/query.html#the-query-object
When reading the simple-salesforce docs, it only shows accessing object metadata using hard-coded methods like such:
sf.Contact.metadata()
Is there no way to do something like this?
sf["Contact"].metadata()
I want to loop through a list of objects and retrieve all these objects fields, but it seems like this isn't possible due to the limitation seen above.
for obj in objects:
fields = [x["name"] for x in sf[obj].describe()["fields"]]
# processing for each object
Is there any way to access object metadata using a string parameter, instead of a hard-coded value?
The sf. interface is actually call to the the get_attr method in the Salesforce class.
get_attr returns the value of SFType(name, self.session_id, self.sf_instance, self.sf_version, self.proxies).
You could do what you would like with the following:
from simple_salesforce import SFType
....
sf_object = ['Case', 'Contact', 'Account', 'Custom1__c', 'Custom2__c']
for each in sf_object:
SFType(each, sf.session_id, sf.sf_instance, sf.sf_version, sf.proxies).metadata()
Hope that helps.
How do you insert objects to a collection in using MongoKit in Python?
I understand you can specify the 'collection' field in a model and that you can create models in the db like
user = db.Users()
Then save the object like
user.save()
However I can't seem to find any mention of an insert function. If I create a User object and now want to insert it into a specific collection, say "online_users", what do I do?
After completely guessing it appears I can successfully just call
db.online_users.insert(user)
You create a new Document called OnlineUser with the __collection__ field set to online_users, and then you have to related User and OnlineUsers with either ObjectID or DBRef. MongoKit supports both through -
pymongo.objectid.ObjectId
bson.dbref.DBRef
You can also use list of any other field type as a field.
I suppose your user object is a dict like
user = {
"one": "balabala",
"two": "lalala",
"more": "I am happy always!"
}
And here is my solution, not nice but work :)
online_users = db.Online_users() # connecting your collection
for item in user:
if item == "item you don't want":
continue # skip any item you don't want
online_users[item] = user[item]
online_users.save()
db.close() # close the db connection
When I make a query in Mongodb using Mongokit in Python, it returns a json document object. However I need to use the return value as a model type that I have defined. For example, if I have the class:
class User(Document):
structure = {
'name': basestring
}
and make the query
user = db.users.find_one({'name':'Mike'})
I want user to be an object of type User, so that I can embed it into other objects that have fields of type User. However it just returns a json document. Is there a way to cast it or something? This seems like something that should be very intuitive and easy to do.
From what I can see Mongokit is built on the top of pymongo, and pymongo find has an argument called as_class:
as_class (optional): class to use for documents in the query result (default is document_class)
http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find