I'm using py2neo to insert some data into my neo4j db.
I create arrays of NodePointers and Relations and insert them with
for i in rels:
test_graph.create(i)
after the process.
During the creation of my arrays I would like to check if a specific NodePointer was already added to the array or not (don't want to create two NodePointers with same name).
Looking for a way to check a NodePointer properties, I've found this at py2neo documentation:
>>> alice.properties["name"]
'Alice'
but when I try to do:
def isThereAThisInHere(this, here):
for i in here:
if (i.properties["name"] == this):
return i
return False
mVar = isThereAThisInHere(defWord.wordVar[0],tempVar)
if (mVar == False):
mVar = Node("Variable",name=defWord.wordVar[0])
tempVar.append(mVar)
I get: 'NodePointer' object has no attribute 'labels'
Does anyone have a solution or suggestion for my problem? Thank you.
The problem was in the (mVar == False) comparison. Even though the error was raised at the .properties["name"] line.
Related
Sorry if this seems like a really stupid question. I am building an app using Django, and at some point I am accessing the db using db.objects.get(var = val)
But my question is what type object does this method return? And hw can I access the data in it?
Like as a dict, list or sth else?
When I use this:
a = db.objects.get(var=val)
print(a["id"])
It returns:
'db' object is not subscriptable
When I use this:
a = db.objects.get(var=val)
print(a)
I get:
db object (1)
I cannot use the data in this form.
It will return a object. See the docs for details.
Use . operator to access values inside object.
print(a.field_name)
It would return the object of your model on which you are querying.
If nothing matches and no rows is returned, it would through a Model.DoesNotExists exception.
I am using the Peewee library in Python and I want to check if a query exists. I do not want to create a record if it doesn't exist, so I don't want to use get_or_create. There must be a better solution than to use try/except with get but I don't see anything. Please let me know if there is a better way. Thanks.
You can use .exists():
query = User.select().where(User.username == 'charlie')
if query.exists():
# A user named "charlie" exists.
cool()
http://docs.peewee-orm.com/en/latest/peewee/api.html?highlight=exists#SelectBase.exists
If you just need to check existence use the accepted answer.
If you are going to use the record if it exists you can make use of Model.get_or_none() as this removes the need to use a try/catch and will not create a record if the record doesn't exist.
class User(peewee.Model):
username = peewee.CharField(unique=True)
user = User.get_or_none(username='charlie')
if user is not None:
# found user, do something with it
pass
Alternatively, if you want to check if e.g. some other table refers this record, you can use WHERE EXISTS (subquery) clause. It is not supported natively by PeeWee, but it can be easily constructed:
subquery = Child.select(Param('1')).where(Child.parent == Parent.id)
parents_with_children = Parent.select().where(
Clause(SQL('EXISTS'), subquery))
It is equivalent to the following SQL:
SELECT * FROM parent
WHERE EXISTS (SELECT 1 FROM child
WHERE child.parent_id = parent.id);
Here I used SELECT 1 for subquery to avoid fetching unneeded information (like child.id). Not sure if such optimization is actually required.
UPD (Feb 2022)
After more than 5 years of peewee evolution, it looks like the Clause class is gone.
The following code may work (I didn't have a chance to test it though):
subquery = Child.select(Param('1')).where(Child.parent == Parent.id)
parents_with_children = Parent.select().where(
NodeList((SQL('EXISTS'), subquery)))
AFAIK, peewee's Model.get_or_create() doesn't return a flag that indicates a creation, unlike django's get_or_create(). Is there a good way to check if an instance returned by get_or_create() is freshly created?
Thanks
There's a section in the docs that should hopefully be helpful: http://docs.peewee-orm.com/en/latest/peewee/querying.html#get-or-create
If the docs are lacking, please let me know and I'll be happy to improve them.
http://docs.peewee-orm.com/en/latest/peewee/api.html#Model.get_or_create
classmethod get_or_create(**kwargs)
Attempt to get the row matching the given filters. If no matching row is found, create a new row.
Parameters:
kwargs – Mapping of field-name to value.
defaults – Default values to use if creating a new row.
Returns:
Tuple of Model instance and boolean indicating if a new object was created.
It also warns you that race conditions are possible with this method, and even gives you an example without using the method:
try:
person = Person.get(
(Person.first_name == 'John') &
(Person.last_name == 'Lennon'))
except Person.DoesNotExist:
person = Person.create(
first_name='John',
last_name='Lennon',
birthday=datetime.date(1940, 10, 9))
According to source code, no way to find out. Also, according to documentation, it is not recommended to use this method.
I suggest to use try/except/else clause.
Hi I am using Flask Peewee and trying to update merchant_details model but it is not working.
Following is the error I am getting:
AttributeError: 'SelectQuery' object has no attribute 'update'
mdetails = merchant_details.filter(merchant_details.merchant_id==session['userid']).update(
merchant_name=request.form['merchantname'],
first_name=request.form['firstname'],
last_name=request.form['lastname'],
)
Please Help!
First, it looks like you are using pre-2.0 syntax (the filter method is now deprecated). I'd recommend looking at the docs for info on the latest version.
Typically, you do not "update a query". The two main ways of accomplishing this is are...
1.) Use a query to retrieve an object, then use the save() method to update the object. For example...
mdetails = MerchantDetails.select().where(MerchantDetails.id == 42).get()
mdetails.name = 'new name'
mdetails.save() # Will do the SQL update query.
2.) Use a SQL update statement...
q = MerchantDetails.update(name='new name')
.where(MerchantDetails.id == 42)
q.execute() # Will do the SQL update query.
Both of these, in essence, accomplish the same thing. The first will make two queries o the database (one to SELECT the record, another to UPDATE the record), while the second will only use one SQL call (to UPDATE the record).
I got the solution
mdetails = merchant_details.update(
merchant_name=request.form['merchantname'],
first_name=request.form['firstname'],
last_name=request.form['lastname'],
street_1=request.form['street1'],
street_2=request.form['street2'],
state=request.form['state'],
city=request.form['city'],
phone=request.form['phone'],
zipcode=request.form['zip'],
).where(merchant_details.merchant_id==session['userid'])
mdetails.execute()
Anyways Thanks Mark
I searched for this solution too and thanks to #Mark and #Rohit I changed my code (peeweee with PostgreSQL) and is working.
To add a small improve it seems the update will be executed even if you will not use the variable. For me is simpler and a cleaner code:
merchant_details.update(
merchant_name=request.form['merchantname'],
first_name=request.form['firstname'],
last_name=request.form['lastname'],
street_1=request.form['street1'],
street_2=request.form['street2'],
state=request.form['state'],
city=request.form['city'],
phone=request.form['phone'],
zipcode=request.form['zip'],
).where(merchant_details.merchant_id==session['userid']).execute()
There is probably a better way of dealing with non existant query sets...!
The problem i have with this code is that it raises an exception if the normal case will be true! That is: if a workspace name with the same name in the db is not existent.
But instead of having an exception i would like to go for a query that does not return DoesNotExist but true or false
My unelegant code:
try:
is_workspace_name = Workspace.objects.get(workspace_name=workspace_name,user=self.user.id )
except:
return workspace_name
if is_workspace_name:
raise forms.ValidationError(u'%s already exists as a workspace name! Please choose a different one!' %workspace_name )
Thanks a lot!
You can use exists() method. Quoting docs:
Returns True if the QuerySet contains any results, and False if not.
This tries to perform the query in the simplest and fastest way
possible, but it does execute nearly the same query as a normal
QuerySet query.
Remarks: the simplest and fastest way. It is cheaper to use exists (than count) because with exists the database stops counting at first occurrence.
if Workspace.objects.filter(workspace_name=workspace_name,
user=self.user.id).exists()
raise forms.ValidationError(u'%s already exists ...!' % workspace_name)
else:
return workspace_name
Checking for the existence of a record.
If you want to test for the existence of a record in your database, you could be using Workspace.objects.filter(workspace_name = workspace_name,user = self.user.id).count().
This will return the number of records matching your conditions. This number will be 0 in case there is none, which will be readily usable with an if clause. I believe this to me the most standard and easy way to do what you need here.
## EDIT ## Actually that's false, you might want to check danihp's answer for a better solution using Queryset.exists!
A word of warning: the case of checking for existence before insertion
Be cautious when using such a construct however, especially if you plan on checking whether you have a duplicate before trying to insert a record. In such a case, the best solution is to try to create the record and see if it raises an exception.
Indeed, you could be in the following situation:
Request 1 reaches the server
Request 2 reaches the server
Check is done for request 1, no object exist.
Check is done for request 2, no object exist.
Proceed with creation in request 1.
Proceed with creation in request 2.
And... you have a duplicate - this is called a race condition, and is a common issue when dealing with parallel code.
Long story short, you should use try, expect and unique constraints when dealing with insertion.
Using get_or_create, as suggested by init3, also helps. Indeed, get_or_create is aware of this, and you'll be safe so long as unwanted duplicated would raise an IntegrityError
obj, created = Workspace.objects.get_or_create(workspace_name=workspace_name, user=self.user.id)
if created:
# everything ok
# do something
pass
else:
# not ok
# respond he should choose anything else
pass
read more at the docs