Django Filter items with OneToOne relationship to Group of Users - sql

In Django, if I have a model such as a Building which is OneToOne related to a (Django Auth) Group containing users, how can I find all the buildings to User belongs to (maybe those are all the buildings the User works in)? Building is one to one with Group so building has a group foreign key field called 'group'.
I've tried
Building.objects.filter(group__contains=user)
Building.objects.filter(group_user_set__contains=user)
I'm getting no matches when there should be matches.

Using contains is not the right choice since it searches for expression inside field (string) not within the set. Try using:
Buildings.objects.filter(group__user=user)

If it's a one to one relationship why not just return the groups?
result = []
u = User.objects.get(your user here)
for group in u.groups.all():
result.append(group.whateverYourForeignKeyFieldIsCalled)
return result

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.

How to list users which belongs to specific group in ldap without backlink enabled

What is the search filter to list users belong to specific group like "engineering" in a ldap server which don't have backlink enabled.
For example, if backlink enabled i can use following filter,
(&(objectClass=person)(memberOf=cn=engineering,ou=Groups,o=company,o=com))
Wanted to know corresponding search query without using memberOf attribute.
Thanks
DarRay
Try your filter as:
(&(objectClass=group)(cn=engineering))
using a base of
ou=Groups,o=company,o=com
and a scope of subtree
Returning attribute "member"
Or even more efficient:
(objectClass=group)
With a base of
cn=engineering,ou=Groups,o=company,o=com
and a scope of base
Returning attribute "member"
-jim
The main question is: How are the users linked to groups?
One way is by specifying the users as attributes in the group. That can be done either via the uniqueMember- or the memberUid-Attribute. To find the users of a certain group you will have to use two queries. One query will retrieve the DNs or UIDs of the users of a group by fetching the uniqueMember or memberUid attribute of the group in question depending on your setup. Then you can retrieve the users by either using (&(objectclass=person)(uid=<uid>)) or (&(objectclass=person)(dn=<dn>)).
The other way is by storing the grous as attributes in the user, which you described above.
Hope that helps.

Search through Users with dynamic attributes with SQL

.Hi i'm working with Asp and SQL-Server and i have no problem with writing dynamic query
I'm trying to Write a search page for searching people.
I have 3 related tables:
See my table diagram in : http://tinypic.com/r/21159go/5
What i'm trying to do is to design a search page that a person can search users with a dynamic number of attributes.
Example:
think that a username called "User1" has 3 attributes named "Attr1", "Attr2" and "Attr3" related to him in "UserAttributes" table and "User2" has 3 attributes named "Attr1", "Attr2" and "Attr4".
Attribute names and other bunch of items unrelated to search function saved in "Attributes" Table. This is because i want to relate an attribute between multiple users. and their values are stored in "UserAttributes" table.
Well someone wants to search upon "Attr1" and "Attr2" and wants to return all users that have "Attr1" and "Attr2" with specific value.
I need a query to know how to implement this. I can write a dynamic query with asp.net so if someone please give me a query for this one example i have brought, i would be thankful
P.S. This is not my real database. my real database is much more complex and has more fields and tables but i just cut it and brought only necessary items. and because attributes are very dynamic they can't be embedded in table columns.
Thanks in advance
Based on your DB diagram your code would be something like this
update:
SELECT u.*
FROM users AS u
LEFT OUTER JOIN UserAttributes AS ua1
ON u.USER_ID = ua1.USER_ID
LEFT OUTER JOIN UserAttributes AS ua2
ON u.USER_ID = ua2.USER_ID
WHERE (
ua1.attribute_id = 'att1'
AND ua.attribute_value = 'MyValue' )
AND (
ua2.attribute_id = 'att2'
AND ua.attribute_value = 'MyValue2' )
In where clause you would specify the attirbute_Id and what value you are expecting out of it. Than just decide if you want to restrict users to have all values match or just one of them, in that case modify AND between statements to be OR
if you just want to do this quick and dirty you can create your own class library that can create adhoc sql that will pass to the database.
if you want more organized matter, create SP that will bring back users and accepts any left of id and value. Do a lot of that by passing list separated by comma, colon or semicolon. Than split it up in SP and filter results based on those values
there are many other alternatives like EntityFramework, LINQ-to-SQL and other options, just need to figure out what works best for you, how much time you want to spend on it and how easy will it be to support later.

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.