select distinct values from JSON using django-mysql - mysql

I'm using this library and my model looks like this:
class PhoneTest(Model):
data = JSONField()
My JSON obj looks something like this (in a real obj there are way more fields):
{
"deviceStatus": true,
"officerCode": 123456,
"imei": 123456789123456
}
For instance, I want to get a list of all officerCodes. How do I do that ? All I've tried so far has not worked. For example this did not:
tests = PhoneTests.objects.all()
tests.distinct('data__mOfficerCode')
It gives me the following error:
NotSupportedError: DISTINCT ON fields is not supported by this database backend
But it's because I'm using this new library, not the native django mysql backend. What are possible workarounds?
I would greatly appreciate any help.

you can use values_list method
PhoneTests.objects.all().values_list('data__mOfficerCode').distinct()

Related

In strapi, that is configured to use MySql, how do I create a new content type record in the code?

y'all,
Within my custom, strapi content type, controller code, what method in the model object do I use to create a new record? My app is configured to use MySql.
The following worked fine when I was using MongoDB, but now with MySql, it doesn't work.
With Mongo, in my code, I was doing this:
let model = strapi.models[modelName];
await model.create({"Name":"<NEW ENTRY>", "Path":ruleData.requestedPath});
, but now, with MySql, I get an error saying that model.create() is not a function. 🤔
Also, when I step into the code, create() is no longer there. I also can't seem to find the equivalent "create" method in the model object, for mysql.
??? Does the strapi ORM, model object change member functions, etc when moving from MongoDB to MySql??? I thought not since that was a big part of the reason for using the ORM.
I suggest you use strapi.query('article') instead of strapi.models.article
So it will be strapi.query('article').create({...})

Output filtering from nodejs while getting data from mongodb

I have an JSON like {'a':'b', 'c':{'e':[{}],'f':[{}]}} I want to query this structure such that i should get only {'a':'b', 'c':{'e':[{}]}} as output. To achieve this i am trying to follow below options mechanism but not able to get the desired output.
var options = {_id:0,'a':1,'c'.'e':1};
How can this be resolved? Any idea.
You almost had it.
Just do like this.
var options = {_id:0,'a':1,'c.e':1};
Im not sure what driver you using, but if you use mongodb native driver http://mongodb.github.io/node-mongodb-native/ this is the example.
collection.find({}).project(options).toArray(function(err, data){
//data will contain desired fields.
})
Hope this helps.

How to get the model name from the table name in CakePHP

In one of my projects, I have a function :
public function select($table){
$model=Inflector::singularize($table);
$result=$this->$model->find('all'));
...........
...........
}
Here, I tried to get the Model name from the given "table name"($table), and used find function of that model to select all data from that table. But that didn't work.
So, what should I do here ? Can anybody please help me ?
Thanks
You can use my trick. create table name as per model name, or using substr() or strstr() you can extract table prefix, then you can use your model ,
$tableName="myprefix_posts";
$dynamicModelName=strstr($tableName,"myprefix_");
$this->loadmodel($dynamicModelName);
if( $this->$dynamicModelName->save($this->data)){
// your code
}
You can use the Inflector class for the table name to be singularized. Example:
$dynamicModel = Inflector::singularize($table);
When you want to use the model via $this->Model you have to load it first.
$this->loadmodel($dynamicModel);
Just a friendly warning: Try not to use words that might be keywords in PHP or MySQL as variable or function names like you do in the function above (select). You or any other developers might get confused at later stages of development. There is probably no harm, I just don't recommend it.
Enjoy

Ruby On Rails map 2 database columns to 2D JSON array

I am trying to grab two columns of data out of a database, using Ruby on Rails ActiveRecord calls and put them into a 2D JSON array for passing to the client.
I have it working for one column. Now I need to get it working for 2 columns.
This is what I have so far for the database call:
select("TOTAL").map{|x| x.TOTAL.ceil}
This is what I have for the controller:
#results = JSON.dump({ :totals => PerformanceResults.find_totals })
This gives me something like this:
{"totals" [145,132,863,693,372,74,838,91,18,172,84,90,373,161,160,173,1910,210,513,14,79,21,84,41,2630,0,93,150,2971]}
To get two columns, this is how I'm starting out, but it's not going well:
Database call:
select("TOTAL, time_stamp ").map{|x| x.attributes.slice(:x.TOTAL.ceil, x.time_stamp)}
Its telling me "undefined method `TOTAL' for :x:Symbol", which I understand, but since I'm new to Ruby on Rails and also JSON, I thought I'd ask for some help in doing this...
My goal is to get this passed to the client: {"totals" [['timestamp', data], ['timestamp', data], etc.... ]}
I have solved this on my own using the following for anyone looking for this solution in the future.
select("TOTAL, time_stamp ").map{|x| [x.TOTAL.ceil, x.time_stamp]}
In rails console, to fetch multiple columns, you could also use the following method. Suppose you have a User table and you wish to print the id's and email's of the users, You have to do it as shown below:
User.all.map{|user| "#{user.id},#{user.email}"}
This is an alternative to what was already explained above.

Raw SQL within Pylons app that uses SQLAlchemy?

I've inherited a Pylons app that uses SQLAlchemy. I know nothing about SQLAlchemy and very little about Pylons :)
I need to run some raw SQL from within the app. The SQLAlchemy currently seems to be working in the following way (example code):
import myapp.model as model
model.Session.query(model.KeyValue) # existing code
.join(model.Key)
.filter(model.Key.name == name)
).count() == 0, name
How do I get it to run raw SQL? I see that I need an execute() statement, but how exactly do I run it? The following both fail:
model.Session.execute('create table hello_world;')
model.Connection.execute("""
create table hello_world;
""")
What's the magic invocation? There's no reference to a Connection object in the existing code, and I'm not sure how to create one.
You can obtain connection that is used by Session by using its connection method:
connection = model.Session.connection()
Then you can issue your query:
connection.execute('create table hello_world;')
Note that in Pylons model.Session is not a sqlalchemy.orm.session.Session class. It's an instance of sqlalchemy.orm.scoping.ScopedSession. That's how it's created in model.meta module:
Session = scoped_session(sessionmaker())
My first impulse is to recommend trying the execute() method of an instance of Connection, instead of the execute() method of the class itself as your example code suggests that you're doing.
Are you working off of the Pylons Book examples ?