I have a Mongo Document with some fields (_id, id, name, status, etc...). I wrote a typical document in a class(like a model would do):
class mod(Document):
id=fields.IntField()
name = fields.StringField()
status=fields.StringField()
description_summary = fields.StringField()
_id = fields.ObjectIdField()
And with this model, I tried to access them:
>>> from mongoengine import *
>>> from api.models import *
>>> connect('doc')
MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True, read_preference=Primary())
I tried to fetch all the entries in the "mod" document: It Worked! I can get all the fields of all the entries (id, name, etc...)
>>> mod_ = mod.objects.all()
>>> mod_[0].name
'Name of entry'
>>> mod_[0].id
102
I tried to filter and return all the entries with the field "status" = "Incomplete": It works, just like before.I tried to filter other fields: it works too
>>> mod_ = mod.objects(status="Incomplete")
>>> mod_[0].name
'Name of entry'
>>> mod_[0].id
102
But When I try to filter with the id I don't manage to get a result:
>>> mod_ = mod.objects(id=102)
>>> mod_[0].name
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/.../lib/python3.4/site-packages/mongoengine/queryset/base.py", line 193, in __getitem__
return queryset._document._from_son(queryset._cursor[key],
File "/.../lib/python3.4/site-packages/pymongo/cursor.py", line 570, in __getitem__
raise IndexError("no such item for Cursor instance")
IndexError: no such item for Cursor instance
>>> mod_[0].id
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/.../lib/python3.4/site-packages/mongoengine/queryset/base.py", line 193, in __getitem__
return queryset._document._from_son(queryset._cursor[key],
File "/.../lib/python3.4/site-packages/pymongo/cursor.py", line 570, in __getitem__
raise IndexError("no such item for Cursor instance")
IndexError: no such item for Cursor instance
So I tried with mod.objects.get(id=102)
>>> mod_ = mod.objects.get(id=102)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/.../lib/python3.4/site-packages/mongoengine/queryset/base.py", line 271, in get
raise queryset._document.DoesNotExist(msg)
api.models.DoesNotExist: mod matching query does not exist.
Mod matching query does not exist, so it doesn't recognize the id field but when I write mod_[0].id I do have a result, so what can be wrong?
EDIT: I believe that when writing mod.objects(id=102), the field id is interpreted as the _id. How can I specify, I want to query by id and not _id? My Document is already written, so I cannot change the name of the fields.
So, the problem does not come from the difference between _id and id, like said #HourGlass. The values of the id field were stored as integer, I wrote fields.IntField() for the id field, and called mod.objects(id=102) (without quotes).
But for some reason, I have to write them as fields.StringField(), and call mod.objects(id='102').
Related
i am running a python Application with Mongo DB Backend.
For an EOS Blockchain Query i need to find out the highest Value for an Attribute called eosTimestamp (String)
I created this code:
def getLastEOSTimestampProperty(client,db):
mydb = client[db]
collection = mydb["properties"]
ensure_index(collection,[('eosTimestamp',-1)])
filter={}
project={
'eosTimestamp': 1
}
sort=list({
'eosTimestamp': -1
}.items())
result = list(client[db][collection].find(
filter=filter,
projection=project,
sort=sort
).limit(1))
maxtimestamp=result[0]['eosTimestamp']
#return(maxblocknum)
return str(maxtimestamp)
When i run this code i get the following Error Message:
Traceback (most recent call last):
File "c:\projects\UplandDB\worker.py", line 408, in <module>
print(getLastEOSTimestampProperty(client,db))
File "c:\projects\UplandDB\worker.py", line 387, in getLastEOSTimestampProperty
result = list(client[db][collection].find(
File "C:\projects\UplandDB\.venv\lib\site-packages\pymongo\database.py", line 237, in __getitem__
return Collection(self, name)
File "C:\projects\UplandDB\.venv\lib\site-packages\pymongo\collection.py", line 212, in __init__
raise TypeError("name must be an instance of str")
TypeError: name must be an instance of str
Do You have any hints what i made wrong?
i'm using replits database but when i try to load it in it returns an error
any ideas?
cookie = db[name]
cookiepc = db[name + "cookiepc"]
increase = db[name + "increase"]
the error is
Traceback (most recent call last):
File "main.py", line 25, in <module>
cookiepc = db[name + "cookiepc"]
File "/home/runner/Cookie-clicker/venv/lib/python3.8/site-packages/replit/database/database.py", line 439, in __getitem__
raw_val = self.get_raw(key)
File "/home/runner/Cookie-clicker/venv/lib/python3.8/site-packages/replit/database/database.py", line 479, in get_raw
raise KeyError(key)
KeyError: 'shdfgwbdhfbadwcookiepc'
According to the documentation for replit-py, a KeyError is raised when an attempt is made to read from a key that doesn't exist in the database.
You can use db.get to specify a default value for if the key doesn't exist:
print(db.get("b", "default")) # default
db["b"] = "pie"
print(db.get("b", "default")) # pie
I want to create multiple databases but I don't know how I can make it
this is python code:
# 1 - for import data in listbox
def clear_item_list():
items.delete(0, END)
# 2 - for import data in listbox
def fill_item_list(items):
for item_ in items:
items.insert(END, item_)
# 3 - for import data in listbox
def item_list_view():
clear_item_list()
items = app.data_1.view()
fill_item_list(items)
# and that for placement data in entries
def get_selected_row_item(event):
global selected_item
if len(items.curselection()) > 0:
index = items.curselection()[0]
selected_item = items.get(index)[:]
item_name.delete(0, END)
item_name.insert(END, selected_item[1])
item_price.delete(0, END)
item_price.insert(END, selected_item[2])
items.bind("<<ListboxSelect>>", get_selected_row_item)
This code is for making a table:
"CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY , Namee VARCHAR , price INTEGER )"
I don't have any idea this is my problem or not, because when I wanna use price, type that data is string and python raise this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Green\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "D:\python\WindowsProject\app\manager\manager_sign_in.py", line 44, in back_to_main_manager
main_screen()
NameError: name 'main_screen' is not defined
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Green\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "D:\python\WindowsProject\app\manager\sign.py", line 33, in back_to_main_mngr
main_screen()
NameError: name 'main_screen' is not defined
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Green\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py", line 1892, in __call__
return self.func(*args)
File "D:\python\WindowsProject\app\main.py", line 33, in user_sign
user_screen()
NameError: name 'user_screen' is not defined
Traceback (most recent call last):
File "D:\python\WindowsProject\app\main.py", line 4, in <module>
from app.user.user_sign_in import *
File "D:\python\WindowsProject\app\user\user_sign_in.py", line 240, in <module>
user_screen()
File "D:\python\WindowsProject\app\user\user_sign_in.py", line 236, in user_screen
item_list_view()
File "D:\python\WindowsProject\app\user\user_sign_in.py", line 55, in item_list_view
fill_item_list(items)
File "D:\python\WindowsProject\app\user\user_sign_in.py", line 48, in fill_item_list
items.insert(END, item_)
TypeError: 'str' object cannot be interpreted as an integer
and this is input data:
(1, 'pizza', '6')
if you can help me pls say to I give you more data about that if you need
The issue is on the below function:
def fill_item_list(items): # <- items is passed argument
for item_ in items:
# "items" below is expected to be an instance of tkinter Listbox
# but it is actually the passed argument (a list object)
items.insert(END, item_)
You used same name on the passed argument as the tkinter Listbox.
Use another name for the passed argument:
def fill_item_list(data): # used "data" instead of "items"
for item_ in data:
items.insert(END, item_)
I have an actor object, and it has both name and id, i could take the name, but it couldn't take the id
look please
>>> actor
<Person id:0000199[http] name:_Pacino, Al_>
>>> actor["name"]
u'Al Pacino'
>>> actor["id"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IMDbPY-5.0-py2.7-macosx-10.6-intel.egg/imdb/utils.py", line 1469, in __getitem__
rawData = self.data[key]
KeyError: 'id'
>>>
Use the .personID property of a Person object:
actor.personID
Here is my code where I am updating record in shelve
def updateRecord(db, form):
if not 'key' in form:
fields = dict.fromkeys(fieldnames, '?')
fields['key'] = 'Missing key input'
else:
key = form['key'].value
if key in db:
record = db[key]
else:
from person import Person
record = Person(name='?',age='?')
for field in fieldnames:
setattr(record, field, eval(form[field].value))
db[key] = record
fields = record.__dict__
fields['key'] = key
return fields
When i am trying to retrieve the value from shelve i am getting this error
>>> import shelve
>>> db = shelve.open('class-shelve')
>>> db['sue'].name
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/shelve.py", line 121, in __getitem__
f = StringIO(self.dict[key])
File "/usr/lib/python2.7/bsddb/__init__.py", line 270, in __getitem__
return _DeadlockWrap(lambda: self.db[key]) # self.db[key]
File "/usr/lib/python2.7/bsddb/dbutils.py", line 68, in DeadlockWrap
return function(*_args, **_kwargs)
File "/usr/lib/python2.7/bsddb/__init__.py", line 270, in <lambda>
return _DeadlockWrap(lambda: self.db[key]) # self.db[key]
KeyError: 'sue'
any insights whats going on?
Assuming in the first snippet, that the db variable is a 'shelf' object, then, although the line...
db[key] = record
...will add the new key/value pair to the 'shelf', it won't necessarily flush the contents to disk, so it won't be available to other processes sharing the same 'shelf file'.
You can force the 'shelf file' to be written to disk by adding the line...
db.sync()
...after adding the new key/value pair, but it can be quite slow when your 'shelf file' gets large, so you may not want to call it too frequently.