So I can fetch a post using this code:
Post post = facebookClient.fetchObject("postId", Post.class, Parameter.with("id", "message","from"));
The "from" field returns the Author's id and name, but not as an User object.
To obtain the User Object I have to send a request again:
User user = facebookClient.fetchObject(post.getFrom().getId, User.class, ..);
This can lead to an insane amount of request calls.
Am I able to fetch them at once?
like this:
MyPost extends Post{
User fetchedUserWithFromFieldId;
}
and somehow invoke:
facebookClient.fetchObject("postId", MyPost.class, Parameter.with("id", "message","from")).deepFetch("fetchedUserWithFromFieldId",User.class, Parameter.with("link","name","location"..etc));
So basically I need the FB equivalent of SQL's join.
Here is the solution:
The parameter fields themselves can be nested.
source: https://restfb.com/documentation/ , Chapter: 'Request with fields (third to n-th level)'
facebookClient.fetchObject("postId", MyPost.class, Parameter.with("id", "message","from{link,name,location}"));
MyPost extends Post{
MyUser user; // MyUser has fields link,name,location.
}
Related
My routes have something like this
return this.store.query('author', {filter:{username : username},
include: 'books, books.readers'})
as we can see author has Many-2-Many relationships with books, book have relationship with reader
How can I include books.reader when run query with author?
Ember Data provides the ability to query for records that meet certain criteria. Calling store.query() will make a GET request with the passed object serialized as query params. This method returns a DS.PromiseArray in the same way as findAll.
So for example in your case author with :username can be changed to the following code:
// GET to /persons?filter[username]=username
this.get('store').query('author', {
filter: {
username: username
}
}).then(function(username) {
// Do something with `username` which can be another filter and whatever else you want, give it a try.
});
Hope it can solve your problem.
class AlbumSerializer(serializers.ModelSerializer):
tracks = serializers.PrimaryKeyRelatedField(many=True, queryset=Track.objects.all(), )
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
what is the format for adding multiple tracks
tracks is a manytomany field
tried array, comma separated but no luck
If I pass
track = "Track1"
where "Track1" is the primary key of Track 1
How to add ['Track1', 'Track2']
Actual code
class TreatmentTemplateSerializer(serializers.ModelSerializer):
icds = serializers.PrimaryKeyRelatedField(read_only=False, many=True, queryset=ICD_10.objects.all())
class Meta:
model = Treatment_template
Screenshot 1
Postman supports array in above format??
Screenshot 2
Screenshot 3
Sending plain JSON objects
I would suggest testing complex request data (including arrays or nested objects) by directly sending JSON rather than form-data or x-www-form-urlencoded. To do this click on raw and paste your JSON object there.
To get a well-formatted JSON object to start with I usually first issue a GET request for a resource that already exists. Then I can just copy the response, change the request method to PUT, click the raw button and paste the json. Then I can start modifying the object and test the endpoint.
In the example above, does the following work?
{
"uuid": "the-long-uuid-here",
"icds": [
"A00",
"A001"
]
}
Update: Put multiple m2m ids with x-www-form-urlencoded
As I wasn't completely happy with not providing an alternative I tested a bit more (with the latest Postman which looks differently).
You can pass multiple values using x-www-form-urlencoded. To do that, add multiple rows with the same label icds and one value at a time.
Notice that I tested it with an endpoint that provides books, which would be icds in your use case. The data in the screenshot will be transmitted as books=1&books=3&last_name=foobar which gets correctly picked up by the DRF endpoint.
Screenshot Postman
I need to write a view to delete multiple objects in one go.
I have modified the HTML template, put checkboxes to select which objects (users) to delete and a button to delete them, but of course you need a view to perform the task.
When you have one item to select at a time, you pass its primary key to the view through the url, how can I extend this to pass more than one primary key?
You would absolutely not be doing this via the URL. If you have a set of checkboxes, then you have a form; since the form is doing destructive operations it will be submitted via POST: therefore your set of IDs is in request.POST.
What you can do is to send the data in a JSON format, which can easily be decoded by Django
On the frontend, you'd have a JavaScript for a button like so,
function delete_object(pks) {
var args = {type: "POST", url: "/delete/", data: {'pks': pks}};
$.ajax(args);
return false;
}
this function would take selected the primary keys from (which is passed in as pks) and POST it to the Django url ^delete/$. A Django view function can then handle the incoming data like so,
def delete(request):
object_pks = request.POST['pks']
Docs.objects.filter(pk__in=object_pks).delete()
How can I resolve a resource_uri during a Tastypie hydrate call?
I am passing the following data object to a Tastypie resource:
{
'date': u'2013-10-31 15:06',
'visitor': u'/visitorlog/api/v1/person/33/',
'purpose': u'Testing'
}
I would like to take the visitor and pull the entire record in a hydrate function, which populates a field with some extra information.
I am currently doing this by splitting out the id and performing a search:
def hydrate_meta(self, bundle):
'''
This will populate the `meta` field with a snapshot of the employee record, if the `empid` is set. This is done so if the employee record changes we retain certain information at the time of the visit.
'''
split_id = bundle.data['visitor'].split('/')
# the id of `visitor` is in `split_id[-2]
# get the record of this visitor from the Django model
person_record = Person.objects.get(pk = split_id[-2])
# ... snipped ... create the `meta_value` object
bundle.data['meta'] = meta_values
return bundle
This is working, but calling split on the resource_uri does not seem the most elegant way to do this.
Is there more effective way to pull a record given a resource_uri?
Resource.get_via_uri(url) (doc) might come in handy.
I was wondering what is the correct approach,
Do I create HiddenInput fields in my ModelForm and from the
View I pass in the primaryKey for the models I am about to edit into
the hiddenInput fields and then grab those hiddenInput fields from
the AJAX script to use it like this?
item.load(
"/bookmark/save/" + hidden_input_field_1,
null,
function () {
$("#save-form").submit(bookmark_save);
}
);
Or is there is some more clever way of doing it and I have no idea?
Thanks
It depends upon how you want to implement.
The basic idea is to edit 1. you need to get the existing instance, 2. Save provided information into this object.
For #1 you can do it multiple ways, like passing ID or any other primary key like attribute in url like http://myserver/edit_object/1 , Or pass ID as hidden input then you have to do it through templates.
For #2, I think you would already know this. Do something like
inst = MyModel.objects.get(id=input_id) # input_id taken as per #1
myform = MyForm(request.POST, instance=inst)
if myform.is_valid():
saved_inst = myform.save()
I just asked in the django IRC room and it says:
since js isn't processed by the django template engine, this is not
possible.
Hence the id or the object passed in from django view can't be accessed within AJAX script.