Django Union Query - django

I need to develop a UNION query in Django with 3 models namely WebQuery,WebReply and BusinessOwners and the output should be of the form below.
{
"(#conversation_id#)_(#b_id#)": {
"from": "(#user_id)",
"email": "(#user_email)",
"date_time": "#get from db",
"query": "are you open ?",
"from_r_id": "(#representative_id)",
"from_r_name": "(#rep_name)",
"business_registered": "FALSE"
"to_business_name": "CCD saket",
"chat": [{
"direction": 1,
"text": "yes sir",
"date_time": "424 577"
}, {
"direction": 0,
"text": "ok",
"date_time": "424 577"
}]
},
I know how to query when only one model is involved, but not sure of the union query.
How will this be achieved?

I personally would say that if this is going to be a common query then I would recommend making a SQL View then querying that.
w3schools has a VERY simple overview of what a view is : http://www.w3schools.com/sql/sql_view.asp
In SQL, a view is a virtual table based on the result-set of an SQL statement.
This means you can write your required sql statement and create a view using this. Then create a django model which mirrors that view which you can then use to query.
So, you will create an SQL view:
CREATE VIEW view_name AS
SELECT a, b, c
FROM table_name
WHERE condition
Then create a django model, which has a slight difference to a normal model:
class view_name(models.Model):
class Meta:
# https://docs.djangoproject.com/en/1.5/ref/models/options/#django.db.models.Options.managed
managed = False
a = models.CharField(max_length)
....
managed = false > https://docs.djangoproject.com/en/1.5/ref/models/options/#django.db.models.Options.managed
You can then query this using the normal django orm syntax
Or there is similar questions:
Previous stackoverflow question, union in django orm
How can I find the union of two Django querysets?

How can I find the union of two Django querysets? provides an example of a union using the '|' operator. I'm not sure how different your models are. If there's common fields you could place those in a separate model and use model inheritance

Related

Using hasMany relation and cascading ORM level in loopback4

I have created 2 models Author and Books where Author has hasMany relation with Book and Book has belongsTo relation with author.
While saving data using ORM models the cascading is not happening i.e
{
"authorId": 1,
"name": "qwery",
"experience": 2,
"books": [{
"BookId": 12,
"category": "string"
}]
}
The above should create a Author record in Author table and create a Book record with the authorId in Book table, which is not happening whereas from belongsTo it can able to create an Author record with just authorId.
You can find the code in the following GIT
You need to create a AuthorBookController to connect the two. Please see example code in here: https://github.com/strongloop/loopback-next/blob/master/examples/todo-list/src/controllers/todo-list-todo.controller.ts

Django Rest Framework filtering a set of item to include only latest entry of each type

I have a list of object of this kind of structure returned in my api
SomeCustomModel => {
itemId: "id",
relatedItem: "id",
data: {},
created_at: "data string"
}
I want to return a list that contains only unique relatedItemIds, filtered by the one that was created most recently.
I have written this and it seems to work
id_tracker = {}
query_set = SomeCustomModel.objects.all()
for item in query_set:
if item.relatedItem.id not in id_tracker:
id_tracker[item.relatedItem.id] = 1
else:
query_set = query_set.exclude(id=item.id)
return query_set
This works by I am wondering if there is cleaner way of writing this using only django aggregations.
I am using Mysql so the distinct("relatedItem") aggregation is not supported.
You should try to do this within sql. You can use Subquery to accomplish this. Here's the example from the django docs.
from django.db.models import OuterRef, Subquery
newest = Comment.objects.filter(post=OuterRef('pk')).order_by('-created_at')
Post.objects.annotate(newest_commenter_email=Subquery(newest.values('email')[:1]))
Unfortunately, I haven't found anything that can replace distict() in a django-esque manner. However, you could do something along the lines of:
list(set(map(lambda x: x.['relatedItem_id'], query_set.order_by('created_at').values('relatedItem_id'))))
or
list(set(map(lambda x: x.relatedItem_id, query_set.order_by('created_at'))))
which are a bit more Pythonic.
However, you are saying that you want to return a list yet your function returns a queryset. Which is the valid one?

Django query annotate and agregate

How can I write a query like this in Django?
select sum(kolvo), reason
from(
select count(reason) kolvo, reason
from contacts group by reason) group by reason
Your query looks semantically equivalent to:
SELECT count(reason) AS kolvo,
reason
FROM contacts
GROUP BY reason
So without the outer query.
You can make such query in Django's ORM with:
Contacts.objects.values('reason').annotate(
kolvo=Count('id')
).order_by('reason')
This will then return a QuerySet that wraps dictionaries, like:
< QuerySet [
{ 'reason': 'some reason', 'kolvo': 13 },
{ 'reason': 'some other reason', 'kolvo': 2 },
] >

Associating multiple items with a single REST call

I am using the Loopback framework, and have modelA which is in a many-to-many relation with modelB.
I want to know if it's possible to relate multiple items from modelB to modelA.
There is currently a way to relate one item with this call:
/modelA/{id}/modelB/rel/{fk}
Is there any way to perform this in a bulk operation?
If I understand your question correctly, I think you can simply do it through a filter. ModelA has many modelBs, Let me assume the relation name is 'modelBs'
modelA.find({
where: [your filter option on model A]
include: {
relation: 'modelBs',
scope: {
[your filters on model B]
}
}
})
in restful way:
/modelAs?filter[include]=modelBs&filter[where]....
The official documentation may help: https://docs.strongloop.com/display/public/LB/Querying+data
It seems to be HasManyThrough model.
I believe your model names starts with lowercase but ideally it should be ModelA and ModelB and their instances can then be saved in modelA and modelB variables.
In order to use add method, you will need to first find instance of ModelA first using ModelA.findById which you can save in modelA variable and then use the following code:
modelA.modelBs.add(modelBFieldsObject, function(err, patient) {
...
});
where modelBs should be the name of relation in the ModalA.json file as in
"relations": {
"modelBs": {
"type": "hasMany",
"model": "ModelB",
"foreignKey": "modelAId",
"through": "ModelAModelB",
"keyThrough": "modelBId"
}
...
I think it should be allowed to pass an array of modelBFieldsObject to create multiple instances as in
modelA.modelBs.add([modelBFieldsObject, modelBFieldsObject], function(err, patient) {
...
});
Tip: For clarity, name your models beginning with upper case letter and their instance variable in camelCase format.
References: Methods added to the model.

How to create relationship using Strongloop strong arc?

How can I create relationships via slc or by directly editing models in a text editor?
I could not find a way to do so using strong arc composer. Does this feature exist?
You cannot create relations using Arc (unfortunately!). It's sure nice to have.
To create relations you can use the command in the cli from the project's root:
slc loopback:relation
This will prompt you with the models available. You can then select the type of relationship you want to have with the selected models. eg, one to many or many to many.
Then you can see the modified .json file in the common folder to view the relations created.
Alternatively, you can also edit the .json file directly. see the example which sets the relation between user and user-tokens
{
"name": "User",
. .
.
"relations": { // relations
"accessTokens": { // specify relation name
"type": "hasMany", // type of relation
"model": "AccessToken", // model to which relation is made
"foreignKey": "userId" // foreign key
}
}
}