Lets continue with the Patient - Physician analogy from the Loopback Docs. Let's make the assumption that Physician model looks like this:
{
"id": "4654654654654654654",
"name": "John Doe"
}
and Patient model looks basiclally the same (only id and name) and two models are connected with HasManyThrough relationship with through model called Appointment as in the docs. https://loopback.io/doc/en/lb2/HasManyThrough-relations.html
My question is, when you GET to /api/physicians url how can you query the response so it includes the appointment date as well as patient for every physician?
Wanted output:
{
"id": "4654654654654654654",
"name": "John Doe",
"patients": [
{ "id": "1321232313", "name": "First Patient", "appointment_date": 1995-12-17T03:24:00 },
{ "id": "1321232313", "name": "Second Patient", "appointment_date": 1995-12-17T03:24:00 }
]
}
Field "appointment_date" is the date from the appointment through model and patient names are obtained through nested including of same model.
Any thoughts?
Use Nested Include Just check link Its help.
Please check this Code :
physicians.find(
{
include: {
"relation": "Appointment",
"scope": {
"fields": ["id", "patientId", "AppointmentDate", "physiciansId"], /*need to include both Person and PersonID fields for this to work*/
"include": {
"relation": "patient",
"scope": {
"fields": {"id": true, "patienName": true},
where: {id: patientId},
}
}
}
}
}
Related
I have this scope defined in my order.json which has relation with branch and customer along with other properties.
"name": "Order",
"properties":{...},
"relations": {...},
"acls": {...},
"scope": {
"include": [
{"relation": "branch", "scope": { "fields": "BranchName" } },
{"relation": "customer", "scope": { "fields": "CustomerName" } }
]
}
This works well as expected in all GET requests with following results
[
{
"OrderDate": "2018-01-12T17:52:21.000Z",
"CustomerId": 39,
"BranchId": 5,
"CustomerRef": "Order by Phone",
...
"CreatedBy": 1,
"id": 1,
"branch": {
"BranchName": "aaaa",
"id": 5
},
"customer": {
"CustomerName": "xxxx",
"id": 39
}
}
]
I was expecting a similar result, however, the response array received after a successful POST request does not include BranchName and CustomerName info from the related models.
Am I doing it correctly? or is there any other way to get back information from related models after a Create/Update operation. I am just trying to avoid another GET request immediately after Create/Update.
You can use the Operation hook after save.
Order.observe('after save', function(ctx, next) {
if (ctx.instance) {
ctx.instance.relatedmodel = someFunctionToGetRelatedModel();
}
next();
});
Whatever is inside the ctx.instance should be included in loopbacks responses.
You just have to figure out how to seamlessly pull the related model details, you want to include.
I have problem in custom serialization and I look in documentation for hours, but I couldn't figure out what I will do. I have nested serializers object like below but I want to have non-nested object, can anyone help me with this?
Nested Object:
{
"id": 1,
"adDate": "20-08-2016",
"price": "30.50",
"city": "Istanbul",
"latitude": "28.987509",
"longitude": "41.040353",
"isPublished": true,
"book": {
"id": 1,
"bookName": "GameOfThrones",
"category": "Adventure",
"photo": "http://localhost:8000/media/advert_images/game_of_thrones.jpg",
"description": "Adventure Book",
"author": "Emre Yavuz",
"language": "Sangridce",
"publicationDate": "2023",
"publisher": "Deu_Yapim",
"edition": "22",
"page_number": 900
}
}
Non-Nested Object:
{
"id": 1,
"adDate": "20-08-2016",
"price": "30.50",
"city": "Istanbul",
"latitude": "28.987509",
"longitude": "41.040353",
"isPublished": true,
"bookName": "GameOfThrones",
"category": "Adventure",
"photo": "http://localhost:8000/media/advert_images/game_of_thrones.jpg",
"description": "Adventure Book",
"author": "Emre Yavuz",
"language": "Sangridce",
"publicationDate": "2023",
"publisher": "Deu_Yapim",
"edition": "22",
"page_number": 900
}
My Serializer Class:
class AdvertSerializer(serializers.ModelSerializer):
book = BookSerializer()
class Meta(object):
model = Advert
fields = ('id', 'adDate', 'price',"city","latitude","longitude","isPublished",'book','seller')
depth = 2
.
class BookSerializer(serializers.ModelSerializer):
photo = serializers.ImageField(max_length=None,use_url=True)
class Meta(object):
model = Book
I don't know why you would prefer a non-nested representation but in order to archive that, you need to specify book fields, one by one on your serializer using the source field attribute.
class AdvertSerializer(serializers.ModelSerializer):
book_name = serializer.CharField(source='book.bookName')
description = serializer.CharField(source='book.description')
# add the rest of the book fields in that way
class Meta(object):
model = Advert
fields = ('id', 'adDate', 'price',"city","latitude","longitude","isPublished",'book','seller')
I'm trying to get a specific field in a api call from an included object.
I get an empty array.
filter =
{"where":{"type":"person"}, "include":["objectA"], "fields":"objectA.name"}
What am i doing wrong?
If for example you have the following data model:
Model: Customer.
Fields: id, name.
Model: Order.
Fields: id, date, description, customerId.
Order.belongsTo(Customer, {foreignKey: ‘customerId’});
You can get only the Customer name by writing this filter:
var filter = {
"where": {
"id": 1
},
"include": [
{
"relation": "customer",
"scope": {
"fields": [
"name"
]
}
}
]
}
Order.find(filter, function(err, order) {
...
})
and in your case i'm guessing the filter suppose to be something like this:
{
"where": {
"type": "person"
},
"include": {
"relation": "objectA",
"scope": {
"fields": ["objectA.name"]
}
}
}
It happens with any object instance that contains embbeded models.
When I attempt to update the father instance, it sets to null its childs PKs.
This is an extract of a json object already updated:
{
"pk": "558d023d153bd41930b3fcf0",
"checkgroup_id": "checkgroupid 5",
"name": "checkgroup five",
"description": "this an example description",
"control_config": {
"control_config_1": {
"pk": null,
"params": {
"param2": {
"pk": null,
"value": "value2",
"mandatory": false,
"default": "default"
},
"param1": {
"pk": null,
"value": "value1",
"mandatory": false,
"default": "default"
}
},
"exceptions": {
"exception1": {
"pk": null,
"description": "description example",
"params": [
{
"pk": null,
"value": "value1",
"mandatory": false,
"default": "default"
},
{
"pk": null,
"value": "value2",
"mandatory": false,
"default": "default"
}
]
}
}
}
},
and this is the Model:
class CheckGroup(models.Model):
"""It defines a set of controls to be applied. """
checkgroup_id = models.TextField(max_length=250)
name = models.TextField(max_length=250)
description = models.TextField(max_length=250)
control_config = DictField(EmbeddedModelField(ControlConfig))
controls = DictField(EmbeddedModelField(Control))
with its serializer defined as:
class CheckGroupSerializer(serializers.ModelSerializer):
""" Transforms CheckGroup into json
"""
control_config = serializers.DictField(child=ControlConfigSerializer())
controls = serializers.DictField(child=ControlSerializer())
pk = serializers.CharField()
class Meta:
""" It lets to choose the model that will be serialize and its fields
"""
model = CheckGroup
fields = ('pk', 'checkgroup_id', 'name', 'description', 'control_config', 'controls')
Well, I found out the reason on django-rest-framework docs.
The problem is that the framework does not deal with that, and should be implemented by us.
The doc says:
Because the behavior of nested creates and updates can be ambiguous, and may require complex dependencies between related models, REST framework 3 requires you to always write these methods explicitly. The default ModelSerializer .create() and .update() methods do not include support for writable nested representations.
I have two Entities: Post and Tag, with a ManyToMany relation called 'tagged'
What I need to do, in order to parse json returned on particular client, is output fields by adding a field 'postID' (the pk field of current Post) to Tag related to that post.
So, my output now is:
{
"post": {
"name": "Dummy name",
"pk": 1,
"tags": [
{
"id": 2,
"name": "Patio"
},
{
"id": 3,
"name": "Roof"
}
],
"ref": "709230056"
}
},
but it should be:
{
"post": {
"name": "Dummy name",
"pk": 1,
"tags": [
{
"id": 2,
"name": "Patio",
"postID": 1,
},
{
"id": 3,
"name": "Roof"
"postID": 1,
}
],
"ref": "709230056"
}
},
I've alrady tried to play with fields of my Handler but with no success :(
How to do that ?
Thanks