Again i have
""" A site message """
class Message( db.Model ) :
# from/to/ a few other fields
subject = db.StringProperty()
body = db.Text()
sent = db.DateTimeProperty( auto_now_add=True )
Now I'm trying to pick out a Message by its KEY. I saved off the key earlier and planted it in an HTML form. The result is a clickable link that looks something like
click to open
So then I run this GQL query:
gql = """select * from Message where __key__='aght52oobW1hZHIOCxIHTWVzc2FnZRiyAQw'"""
But its not working because
BadFilterError: BadFilterError: invalid filter: __key__ filter value must be a Key; received aght52oobW1hZHIOCxIHTWVzc2FnZRiyAQw (a str).
I'm totally missing something here, and that is how do you put an object into a GQL query string.. and not have Gql parser complain of that it is a string?
Don't bother with GQL for key-based retrieval -- make a key object from the string:
k = db.Key('aght52oobW1hZHIOCxIHTWVzc2FnZRiyAQw')
and just db.get(k). If you insist on GQL, btw, that k -- a suitably constructed instance of db.Key, NOT a string object!-) -- is also what you need to substitute into the GQL query (by :1 or whatrever).
You can also construct a query by hand by constructing "an entity key literal, with...a complete path of kinds and key names/IDs".
SELECT * FROM Message WHERE __key__ = KEY('Message', 'message_key')
This is even more helpful if you are using the Datastore Viewer/Explorer and can't use Python syntax.
Related
I'm trying to use the document storage of MySQL 8 in my python project(python 3.8). The version of MySQL-connector python is 8.0.20. According to the API reference and the X DevAPI User Guide, I tried to get the auto increment document ID after adding a document into the DB. Each time after the execution, the data would be inserted into DB successfully, but '-1' would be returned after get_autoincrement_value() was invoked.
My code is just like below:
try:
schema = session.get_schema('my_schema')
collection = schema.get_collection('my_collection')
topic_dict = protobuf_to_dict(topic)
doc_id = collection.add(topic_dict).execute().get_autoincrement_value()
logger.debug('doc_id: {}', doc_id)
return doc_id
except Exception as e:
logger.exception("failed to add topic to db, topic: {}, err: {}", topic, e)
Is there anything wrong with my usage? Thank you all~
Seems like you are interested in the document id that has been auto-generated. If that is the case, you should instead use get_generated_ids:
doc_id = collection.add(topic_dict).execute().get_generated_ids()[0]
In this case, the method returns a list of all the ids that were generated in the scope of the add() operation.
The documentation is probably not clear enough, but get_auto_increment_value() only contains useful data if you are inserting a row with either session.sql() or table.insert() on a table containing an AUTO_INCREMENT column. It has no meaning in the scope of NoSQL collections because in the end a collection is just a table created like (condensed version):
CREATE TABLE collection (
`doc` json DEFAULT NULL,
`_id` varbinary(32),
PRIMARY KEY (`_id`)
)
Which means there isn't anything to "auto increment".
Disclaimer: I'm the lead developer of the MySQL X DevAPI Connector for Node.js
I'm trying to query the database with:
fields = "property_1, property_2, ... property_n"
query = "SELECT {0} FROM Table WHERE property_{n+1} = '{1}'".format(fields, property_{n+1})
all_objs = CacheDatastore.fetch(query, refresh=True)
The problem is that the returned list is empty, while if the query is like
"SELECT * FROM Table WHERE property_{n+1} ='{1}'", I receive the full set.
I've created the necessary indexes and have deployed them, so it is not from there.
The log says that a Blob key is not found, but none of the properties is different from string, float or int...
It turned to be a bug in the db library which is no longer in development, so I'm leaving here the link to the ticket and the comments on it.
GAE allows indexing of static members of the db.Model class hierarchy, but returns 0 results for projection queries where the static member is included
among the projected properties.
https://code.google.com/p/google-cloud-platform/issues/detail?id=119
There is a similar question here - Raw query must include the primary key
However I'm running off of a legacy DB and therefore can't figure out what the issue is with the Primary Key.
This is my RAW query -
trg = Trgjob.objects.db_manager('AdmiralDEV').raw("""
SELECT jobdep_id, jm.jobmst_id, jobdep_type, (jm1.jobmst_prntname + '\' + jm1.jobmst_name) AS jobdep_jobmst,
jobdep_operator, jobdep_status, jobdep_joblogic, jobdep_ingroup, jobdep_dateoffset, jobdep_instoffset,
jobdep_canignore, jobdep_filename, jobdep_filetype, jobdep_fileextent, nodmst_id, varmst_id, jobdep_value
FROM Jobdep jd
INNER JOIN Jobmst jm ON jd.jobmst_id = jm.jobmst_id
INNER JOIN Jobmst jm1 ON jd.jobdep_jobmst = jm1.jobmst_id
WHERE jm.jobmst_id = 9878""")
On the DB works fine, but in django I get the following failure -
Raw query must include the primary key
The primary key on this model is "jobdep_id" as seen in the models.py here -
class Jobdep(models.Model):
jobdep_id = models.IntegerField(primary_key=True)
Try to write query as:
"SELECT jobdep_id AS id ..."
maybe it helps.
If you use Manager.raw() it's required to provide the id. (https://docs.djangoproject.com/en/2.2/topics/db/sql/#performing-raw-sql-queries)
There is only one field that you can’t leave out - the primary key
field. Django uses the primary key to identify model instances, so it
must always be included in a raw query. An InvalidQuery exception will
be raised if you forget to include the primary key.
But you can execute custom SQL directly to avoid this. See more on Django documentation
https://docs.djangoproject.com/en/2.2/topics/db/sql/#executing-custom-sql-directly
The issue was indeed my models.py I had to update it as follows -
class Jobdep(models.Model):
jobdep_id = models.IntegerField(db_column='jobdep_id', primary_key=True)
I am accessing Postgre database using SQLAlchemy models. In one of models I have Column with UUID type.
id = Column(UUID(as_uuid=True), default=uuid.uuid4(), nullable=False, unique=True)
and it works when I try to insert new row (generates new id).
Problem is when I try to fetch Person by id I try like
person = session.query(Person).filter(Person.id.like(some_id)).first()
some_id is string received from client
but then I get error LIKE (Programming Error) operator does not exist: uuid ~~ unknown.
How to fetch/compare UUID column in database through SQLAlchemy ?
don't use like, use =, not == (in ISO-standard SQL, = means equality).
Keep in mind that UUID's are stored in PostgreSQL as binary types, not as text strings, so LIKE makes no sense. You could probably do uuid::text LIKE ? but it would perform very poorly over large sets because you are effectively ensuring that indexes can't be used.
But = works, and is far preferable:
mydb=>select 'd796d940-687f-11e3-bbb6-88ae1de492b9'::uuid = 'd796d940-687f-11e3-bbb6-88ae1de492b9';
?column?
----------
t
(1 row)
I have a productpart database containing a string property named 'type'.
What I'm trying to do is to get all products by a given type (sometimes more then one type).
I've tried to use GAE filter method but can't get it to work properly.
The only solution I've got working is to make a new db.GqlQuery for each type.
The reason I need to fetch each by type is to display them in different 's on the client side?
Is there a way to use just one query for this?
Currently it looks like this :
productPartsEntries = {
'color' : db.GqlQuery("SELECT * FROM ProductParts WHERE type = :type", type = 'color'),
'style' : db.GqlQuery("SELECT * FROM ProductParts WHERE type = :type", type = 'style'),
'size' : db.GqlQuery("SELECT * FROM ProductParts WHERE type = :type", type = 'size')
// add more....
}
..fredrik
You can use the IN operator. It would create the three different queries and group the results together for you under the scenes. See the docs:
GQL does not have an OR operator.
However, it does have an IN operator,
which provides a limited form of OR.
The IN operator compares value of a
property to each item in a list. The
IN operator is equivalent to many =
queries, one for each value, that are
ORed together. An entity whose value
for the given property equals any of
the values in the list can be returned
for the query.
Note: The IN and != operators use multiple queries behind the scenes.
For example, the IN operator executes
a separate underlying datastore query
for every item in the list. The
entities returned are a result of the
cross-product of all the underlying
datastore queries and are
de-duplicated. A maximum of 30
datastore queries are allowed for any
single GQL query.