Can you project multiple aggregates from a single QueryOver - nhibernate

I can create a single aggregate projection on a collection of entities
example
Return the number of shops that are active
But is there a way to project the number of a bunch of different summations in the same query over?
example
number of shops that are active?
Number of shops with active products?
Number of inactive shops?
Then ultimately project these into new properties using the select method.
If you can't do it all within one queryover is there a way to create individual sub queries and join them together to project them (as new properties) into one object?

I don't think you can do it with a single QueryOver, because QueryOver is just a wrapper for Criteria.
You can use multi criteria for this. Create several QueryOvers and use the property UnderlyingCriteria to add it to the MultiCriteria.

Related

How to create a temp boolean field with Django orm

Image I have following models:
class Product(models.Model):
name = models.CharField(max_length=20)
class Receipt(models.Model):
product = models.ForeignKey(Product)
user = models.ForeignKey(User)
I have an input list of product ids and a user. I want to query for each product, whether it's been purchased by this user. Notice I need a queryset with all exist products based on given input because there are other fields I need for each product even not purchased by this user, so I cannot use Product.objects.filter(receipt__user=user).
So can I create a temp Boolean field to present this property in one single query? I am using Django 1.8 and postgresql 9.3
Update requirements:To separate products into two groups. One is bought by this specific user, the other one is not. I don't think any given filter can implement this. This should be implement by creating a new temp field either by annotate or F expression.
I think, you need .annotate() expression as
from django.db.models.expressions import Case, When, Value
product_queryset = Product.objects.annotate(
is_purchased=Case(
When(receipt__user=current_user, then=Value('True')),
default=Value('False')
))
How to access the annotated field?
product_queryset.first().is_purchased
Thx for #JPG's answer.
I just realize except conditional expressions, there's another easy way to do it.
Just using prefetch_related will implement everything in two queries. Although it's double than conditional expressions, but it's still a considerable time complexity solution.
products = Product.objects.filter(id__in=[1,2,3,4,5]).prefetch_related ('receipt_set').all()
Then we can detect user for this product in Python by
for p in products:
print user in [receipt.user_id for receipt in p.purchase_set.all()]

Entity joining in xml

I have run into a little roadblock in regards to joining mantle entities. I would like to have a single depicting fields from two mantle entities, but am unsuccessful in joining them. Specifically, I have linked a list of party relationships (as contacts) to a single partyId (vendor), with the goal to make a vendor contacts page. However I am unable to link that form-list with the PartyContactMech and ContactMech entities (in order to display email and phone number in the same form-list). More generally, my question is how can one map lists to each other the same way one can map a list to a single object (using entity-find-one and value-field does not work when tried with entity-find)?
There is no need to make a view-entity (join entities) to do that. Simply do a query on the PartyRelationship entity in the main 'actions' part of your screen specifying the toParty (vendor). Then in your Form-List, use 'row-actions' to query the PartyContactMech and so on for each fromPartyId (contact) entry that the previous query returned. Also have a look at the PartyViewEntities file in Mantle USL. There are some helpful view-enties already defined for you there such as PartyToAndRelationship, PartyFromAndRelationship etc. Also note that entity-find-one returns a single "map" (value-field) as it queries on the PK. Whereas entity-find returns a list of maps (list). They are separate query types. If I understand your question correctly.

Django: access and update a variable on which to filter during a Django model query?

I'm hoping to build a Django query to my model that lets my filter change as the query progresses.
I have a model Activity that I'm querying for. Each object has a postal_code field and I'm querying for multiple zip codes stored in an array postal_codes_to_query across a date range. I'd like to ensure that I get an even spread of objects across each of the zip codes. My database has millions of Activities, so when I query with a limit, I only receive activities that match zip codes early on in postal_codes_to_query. My current query is below:
Activity.objects.filter(postal_code__in=postal_codes_to_query).filter(start_time_local__gte=startTime).filter(start_time_local__lte=endTime).order_by('start_time_local')[:10000]
If I'm searching for say 20 zip codes, Ideally I'd like to receive 10000 activities, with 500 activities for each zip code that I queried on.
Is this possible in Django? If not, is there some custom SQL I could write to achieve this? I'm using a Heroku Postgres database in case that matters.
You can't do this in a single query, either in Django nor (as far as I know) in SQL.
The best bet is simply to iterate through the list of zips, querying for max 500 in each one:
activities_by_zip = {}
for code in postal_codes_to_query:
activities = Activity.objects.filter(postal_code=code).filter(
start_time_local__gte=startTime).filter(
start_time_local__lte=endTime).order_by('start_time_local')[:500]
activities_by_zip[code] = activities
Of course, this is one query per zip, but I think that's the best you're going to do.

How to determine number of children of a record?

Good afternoon everyone!
I'm studying NHibernate, and decided to make some changes. Among them, I noticed that some fields are unnecessary. So I bring my doubt:
I have a list, let's call it Class_List within each study class, I can have N students for each class. Within the list Class_List, I also have other properties as simple as the name of the class.
How I see it is unnecessary to store how many students I have in the database, I would, in a single query, how many records I have. This, using NHibernate.
Is this possible? How?
Best regards,
Gustavo.
Edit: I've forgot to say one thing... I want to return this number of record, as a column. But this column is not mapped in my .hbm.xml file.
If students are mapped as a collection on Class, you can try using something like this:
var numberOfStudents = session.CreateCriteria<Class>()
.Add(Restrictions.IdEq(1))
.CreateCriteria("_students", "students")
.SetProjection(Projections.RowCount())
.UniqueResult<Int32>();
Where '1' is the id of the class (you can use other property) and '_students' is the name of the students collection.

Kohana 3 ORM: Getting most repeated values, ranked, and inserting into new object / array

So, another in my series of Kohana 3 ORM questions :)
I have, essentially, a pivot table, called connections. The connections table connects a song to a keyword. That's all great and working (thanks to my last two questions!)
I want to output the most connected songs by keyword. So, to somehow query my connections table and output an object (with an arbitrarily limited number of iterations $n) that ranks songs by the number of times they have been connected, ie. the number of times that particular song_id appears for that particular keyword_id.
I have literally no idea how to achieve this, without querying every single row (!!!) and then counting those individual results in an array.... There must be a more elegant way to achieve this?
I believe this is more of an SQL question. Using the DB query builder:
DB::select('songs.*')->select(array('COUNT("keywords.id")', 'nconnections'))
->from('songs')
->join('connections', 'LEFT')->on('connections.song_id', '=', 'songs.id')
->join('keywords', 'LEFT')->on('connections.keyword_id', '=', 'keywords.id')
->group_by('songs.id')
->order_by('nconnections')
->as_object('Model_Song')
->execute();
or in SQL
SELECT `songs`.*, COUNT(`keywords`.`id`) AS `nconnections` FROM songs
LEFT JOIN `connections` ON `connections`.`song_id` = `songs`.`id`
LEFT JOIN `keywords` ON `connections`.`keyword_id` = `keywords`.`id`
GROUP BY `songs`.`id` ORDER BY `nconnections`
should return the result you want.
You'll want to have an accessible property called nconnections in your song model. The simplest way to do that is to add a public member so you don't tamper with ORM's inner workings.
I'm assuming you're using a model called 'Song', linked to a 'songs' table, a 'Keyword' model linked to a 'keywords' table and in the 'connections' table foreign keys 'song_id' and 'keyword_id' for each model respectively.