How to access all the entries in MySQL table in Django View? - mysql

I am designing a Web Application using Django Framework. I have written the model code, urls.py and view code which can be seen Here.
I have added some data into the database table. But when I try to access the object using the code below, it just shows bookInfo objects five times. I don't think I am successful enough in pulling the data from the database. Kindly help.
View
def showbooks(request):
booklist = bookInfo.objects.order_by('Name')[:10]
output = ','.join([str(id) for id in booklist])
return HttpResponse(output)

You are iterating through the object list, you just need to reference the column/attribute you want:
output = ','.join([obj.id for obj in booklist])
Alternatively you can more more finely craft you original db call, then the iterable you use will work. In this case we'll pull out a list of the 'id' attribute.
booklist = bookInfo.objects.order_by('Name').values_list('id', flat=True)[:10]
output = ','.join([id for id in booklist])

I think you are successful in pulling the data. It is just that booklist contains objects, not numeric ids. You can add __unicode__ method to you class BookInfo that is supposed to return a string representation of the object (probably book name in this case). This method is going to be invoked when str() is applied. You can find more info about __unicode__ here.

Related

What is the correct way to handle a POST request in Django class based view?

In my class based view I am handling a post request (which is an AJAX call).I am inserting some data in a database table and returning some json to the frontend.
def post(self,request,*args,**kwargs):
result_data = {}
doc = kwargs['doc']
doc_obj = Document.objects.get_document(doc)
doc_id = doc_obj.doc_id
reference_obj = Reference.objects.save_to_db(request,doc_id)
friendly_name = reference_obj.friendly_name
result_data['friendly_name'] = friendly_name
return HttpResponse(json.dumps(result_data),content_type='application/json')
My question is that is this the right way of handling a post request?My doubt arises here - I am writing some data into database and returning a json of properties of the same data I have written to the database.
Should I do it differently, ie first storing some data in database and returning just id of the row and again making GET request on the same URL?
I would say if it is an API, it is best to minimize the number of queries by returning the whole object the way you did. In case it is to serve a web user interface, it is simpler to return the id and get the rest of the data, if it needs to be displayed, from the client itself.
Either way is fine. The gain is negligible. I have also seen applications give a local positive feedback and then replace with a negative one if the request was unsuccessful. The technique can improve responsiveness, which is always appreciated.
Django-rest-framework returns the json of the inserted object, so i would think it reasonable to copy that behaviour.

How to query mongoDB using mongoose?

How do you query MongoDB using mongoose with node.js? I have it to where I can insert my JSON object to my DB, but all the ways I have tried to return the JSON object from the DB return null or just information about the database.
Is there some good method using mongoose to be able to query the database similar to the method:
var cursor = db.collection.find()
var JSONobject = cursor.next()
Here's what is in my code right now:
mongoose.connect('mongodb://localhost/myDB');
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
var cursor = mongoose.connection.db.contents.find();
console.log(cursor.next());
This throws an error at the line :
var cursor = mongoose....
claiming 'cannot call method 'find' of undefined'.
Note, that my collection 'contents' does in fact exist, and it contains one JSON document. I know this because I manually navigated to the collection using the mongo shell.
Edit: I am open to alternative methods to querying the database. I simply just want to be able to return JSON objects from my DB one at a time, while keeping track of where the client is at in the database.
One method to query mongoDB using mongoose is as follows:
Content.findOne().exec(function(err,docs){console.log(docs)});
Docs contains the JSON object. Access its attributes like any other object.
Note, this method uses asynchronous call backs. As such, you can't store the JSON object docs to a variable in order to use the JSON document information outside of the function. Therefore, you need to perform whatever actions needed with the JSON docs object information inside of the function.
For example, I was needing the query information to provide the filepath for my get api. As such, the result was as follows:
//get
app.get('/api/media/', function(req,res){
Content.findOne().exec(function(err,docs){res.sendFile(path.join(__dirname, '/api/media/', docs.filename))});
});
Note, Content is the model of my schema, and one of its parameters is filename.

cakephp retrive data from one table excluding the associated tables

I am struggling with a basic problem. i am using cake php 2.5. i try to apply the find query in the company model and receiving all the data from companies and with its associations, but i only want to receive the data from company table and want to exclude the data from rest of relationships, can anyone help me with this. below are my queries.
$this->loadModel('Company');
$fields=array('id','name','logo','status');
$conditions=array('status'=>1);
$search_companies = $this->Company->find('first',
compact(array('conditions'=>$conditions,'fields'=>$fields)));
print_r($search_companies);die();
echo json_encode($search_companies);die();
With out seeing your data output, I am just going to take a stab at the problem.
Inside your $search_companies variable you are getting a multidimensional array probably with the other values of the other tables.
Why not just select the one array:
$wantedData = $search_companies['Company'];
// The key Company (which is the model) should be the data you are wanting.
Try setting model's recursive value to -1
$this->Company->recursive = -1;
$search_companies = $this->Company->find('first',
compact(array('conditions'=>$conditions,'fields'=>$fields)));
With this you will not fire the joins queries and therefore you only retrieve model's information.
Cakephp provide this functionality that we can unblind few/all associations on a any model. the keyword unbindModel is used for this purpose. inside the unblindModel you can define the association type and model(s) name that you want to unblind for that specific association.
$this->CurrentModelName->unbindModel(array('AssociationName' => array('ModelName_Youwwant_unblind')));

How to model data for a JSON API and a Document Database

I am making a simple REST API in front of a NoSQL database that stores records as documents similar to JSON (but not exactly the same). Each record has some fields, including id for the database, and also including some derived fields, like dateCreated.
Any time I GET anything, I want to return the objects with all the fields.
// GET /users returns an array of these in JSON
// [{id:"xxx", name:"Bobby", dateCreated:"YYYY-MM-DD"]
data User = User { id :: String, name :: String, dateCreated :: XXX }
But any time I POST or PUT anything, they client should send an object with the id field and any derived fields missing. The database is responsible to create the id when I save it, and I would create some derived fields
// POST /users would need you to post only the name.
// {name:"Henry"}
data PartialUser = PartialUser { name :: String }
If resource represents objects of type User, what should I call the thing client is sending to me? Would you make all the derived fields Maybe values? Or would you create a second object called PostedUser or something?
It can be many things:
a request body
the representation of the intended resource state of the client
a command DTO which you can send to the domain logic in order to process it by CQRS
I would make it CreateUser command, but if you don't want to use CQRS and DDD, then you would probably call it as PartialUserRepresentation, or you don't create a data structure, just use the properties to create a new User entity. Ofc. if you use entities.
So I would say it depends on the architecture of your system.

ServiceNow - JSON Web Service, display related tables

I'm working on a C# program that retrieves data from a ServiceNow database and converts that data into C# .NET objects. I'm using the JSON Web Service to return my data in JSON format.
What I want to achieve is as follows: If there is a relational mapping between a value (for
example: I have a table called Company, where CEO is not a TEXT field but an sys_id to a Employee Table) I want to be able to output that data not with an sys_id (or just displaying the name property by using the 'displayvariable' parameter) but by an object displayed in JSON.
This means that the value of a property should be an object in JSON instead of just a single value.
A few examples:
// I don't want the JSON like this
{"Company":{"CEO":"b181e841c9212c008aeb36850331fab2"}}
// Or by displaying the name of the sys_id table
{"Company":{"CEO":"James Henderson" }}
// I want the data as follows, so I can have all the data I need inside a single JSON record.
{"Company":{"CEO":{"name":"James Henderson", "age":34, "sex":"male", "office":"SBN Left Floor 23"}}}
From reading the documentation I couldn't find anything in the JSON Web Service that allowed me to display the information like this nor
find any other alternative. It should have something to do with joining the tables and displaying it all in the right format.
I have been using SNC for almost three years and have not found you can automatically join tables in a web service. Your best option would be to use a scripted web service which possibly takes a query parameter and table parameter. Then you can json serialized your result as you see fit.
Or, another option would be to generate a new processor that will traverse the GlideRecord object. The ?JSON parameter you pass in to the URL is merely a flag to pass your request to a particular processor. Unfortunately the OOB one I believe is a Java class not a JS script, so you would need to write a script much like I mentioned earlier to traverse the object path serializing the object graph as far down as your want to go.