Django ORM filter in multiple columns - filter

I'm new to Django and Web frameworks.
I have a question regarding Django ORM Filter querying
Order is a Table which references to another table named Show. Show has 3 managers say manager, manager_2, manager_3.
Now I want to pick the Orders, whose users are either of these 3 managers.
How do i do that.
I'm looking for some thing like this:
Order.objects.filter(
order_cancelled__isnull = True,
(show__manager = user || show_manager_2 = user || show_manager_3 = user))

Found the answer.
Can use Q
from django.models import Q
Order.objects.filter(
Q(show__manager = user) | Q(show_manager_2 = user) | Q(show_manager_3 = user),
order_cancelled__isnull = True
)

Related

LINQ query JOIN two tables for Web API controller method

I am really poor at LINQ and can't figure out a simple problem. I have a MVC Web API that has a controller. I have a method inside the controller to return back data for comments entered by user for an item.
The data structure is simple - Comments and User tables with UserID column acting as the foreign key
To solve the problem, I have the following method, which has a LINQ query to do a join between Comments and User tables and return back an object in a new extended object that combines the Comments and User details. I cant seem to grab data from the User table. Can someone please help?
public IQueryable<CommentsWithUserDetails> GetReviewsWithUserByItem(int ID)
{
var query = from x in db.Comments
join y in db.Users on x.CommentsUserID equals y.UserID into z
where x.CommentsItemID.Equals(ID)
select new CommentsWithUserDetails
{
CommentsUserID = x.CommentsUserID,
CommentsText = x.CommentsText,
CommentsRating = x.CommentsRating,
CommentsDate = x.CommentsDate,
UserFirstName = y.FirstName,
UserLastName = y.LastName,
UserPictureURL = y.PictureURL
};
return query;
}
The solution is just to remove the 'into z' part from the query, yes as simple as that!
As pointed by #Nilesh and #Gert Arnold

LINQ partial crosstab query when the potential columns are not fixed

I have a requirement to produce an "flattened" version of data for export, in which the customer wants the related table rows to appear as columns. We're using Entity Framework 4 & .NET 4.0
The customer has the ability to create custom questions for their events. There may be zero to infinite questions. Users attending the event may answer none, some or all of those questions.
What I need to produce is like this:
User 1 User 1 info field A User 1 info field B User 1 Answer to question A User 1 Answer to Question B
User 2 User 2 info field A User 2 info field B User 2 Answer to question A User 2 Answer to Question B
Creating the user info portion of the result set is not problem, but I'm stumped on how to take my related questions and answers, i.e.:
from urf in tblUserRegistrationFields.Include("tblRegistrationFields")
where urf.UserID == eachUserID && urf.tblRegistrationField.EventID == thisEventID
select new
{
FieldLabel = urf.tblRegistrationField.FieldLabel, //this is the question name
value = urf.value //this is the user's answer
}
And add those to my user select statement as individual columns, i.e.:
var users = from u in context.tblUsers
<snip>
select new
{
UserID = u.UserID,
<snip>,
CustomQuestionA = AnswerA,
CustomQuestionB = AnswerB,
... etc.
};
Ultimately I need to create a grid which I can then export to their desired format and I'm open to non-LINQ solutions (although the purchase of 3rd party controls is not an option.) I suspect there is a way to leverage LINQ's grouping features, but I haven't been able to apply it to this scenario.
I found a way to do dynamic pivots in SQL, but couldn't get it to work with two related tables, only with one. Dynamic SQL pivots here:
http://www.simple-talk.com/blogs/2007/09/14/pivots-with-dynamic-columns-in-sql-server-2005/
Ultimately, I fell back and created a dataset manually. It's certainly not an optimized solution, but it gives the customer what they want. I wouldn't recommend this approach for a high volume of data.
I create the dataset and datatable fixed columns, then loop through the list of questions:
//get the list of questions
var context = new EventRegistrationEntities();
var customQuestions = from rf in context.tblRegistrationFields
where rf.EventID == vEventID
select new
{
RegistrationFieldID = rf.RegistrationFieldID,
FieldLabel = rf.FieldLabel
};
//add a question column for each question
List<string> extracolumns = new List<string>();
foreach (var q in customQuestions)
{
dt.Columns.Add(q.FieldLabel, typeof(string));
//store the question names for later user
extracolumns.Add(q.RegistrationFieldID.ToString() + "-" + q.FieldLabel.ToString());
}
Next I then loop through the list of users and insert the fixed data, then within that loop (ugh) I add the users' answers:
foreach (var c in extracolumns) //these are the custom *questions*
{
int regID = Convert.ToInt32(c.Substring(0, c.IndexOf("-")));
string question = c.Substring(c.IndexOf("-") + 1); //we need to pass the question text (aka column header) in because if the user hasn't answered the question we have no access to it from here
//get the question answer
var userAnswer = (from urf in context.tblUserRegistrationFields.Include("tblRegistrationFields")
where urf.UserID == u.UserID && urf.RegistrationFieldID == regID
select new
{
Question = urf.tblRegistrationField.FieldLabel,
Answer = urf.value
}).FirstOrDefault();
//add the answer to the data row
if (userAnswer != null)
{
dr[question] = userAnswer.Answer.ToString();
}
else
{
dr[question] = ""; //if the user has not answered the question, insert a blank
}
}

LINQ to sharepoint . join list help

I am currently using SharePoint 2010,and in my business layer I am using LINQ to SharePoint. I generated all my Entity classes using SPMetal.
We are creating a Library system, my system has 2 Lists . The first one is Contribution and the second one is Contributor. Each Contributor contains a reference to the Contribution List (a PrimaryISBN reference). The Contribution List contains list of books and PrimaryISBN is not unique in this list.
Contribution
ID PrimaryISBN TITLE
1 PRIM1 HardcoverLOTR
2 PRIM1 AudioBookLOTR
3 PRIM2 HardcoverHP
Contributor
ID Name PrimaryISBNLookup
1 ABC PRIM1
2 DEF PRIM2
I am currently trying to fetch All the Books Contributed by a Particular user based on the Name.
My query is something like this
var result = from _contributor in data.contributor
where _contributor.Name= "ABC"
select new Book
{
Title = contributor.PrimaryISBNLookup.Title
}
The problem that I am currently facing is in retrieving records that have same ISBN but different title (Each format will have a title i.e. a Audio book will have a title and a Hardcover of the same book will have a different one).
This query returns me only 1 records even thought I have 2 records in my system i.e. the record with ID (in Contribution) that I am forced to insert during the insertion of record into Contributor List.
Your help is highly appreciated.
From what I understand, you try to implement a simple join, like this:
var results = from _contributor in data.contributor
join _contribution in data.contribution
on _contributor.PrimaryISBNLookup equals _contribution.PrimaryISBN
where _contributor.Name == "ABC"
select new Book
{
Title = _contribution.Title
}
If you want to use DataTable in SPList, try this:
SPList cList = spWeb.Lists.TryGetList("Customer");
SPList oList = spWeb.Lists.TryGetList("Order");
DataTable cTable= cList.Items.GetDataTable();
DataTable oTable= oList.Items.GetDataTable();
var coList = from tbl1 in cTable.AsEnumerable()
join tbl2 in oTable.AsEnumerable() on tbl1["Title"] equals tbl2["CustomerName"]
select new
{
ItemName = tbl2["Title"],
CustomerName = tbl1["Title"],
Mobile = tbl1["MobileNo"]
};

Optimizing LINQ to Sharepoint

I have three lists on Sharepoint 2010 and I have working code that gets the lists and relates them. My problem is that it takes around 15 seconds to load my page. I am a rank beginner with LINQ to Sharepoint and LINQ in general. MY question is: Is there a way to make this code run faster?
SeatingChartContext dc = new SeatingChartContext(SPContext.Current.Web.Url);
EntityList<Seating_chartItem> seatCharts = dc.GetList<Seating_chartItem>("seating_chart");
EntityList<UsersItem> users = dc.GetList<UsersItem>("users");
EntityList<Excluded_usersItem> exusers = dc.GetList<Excluded_usersItem>("excluded_users");
// EntityList<LogsItem> logs = dc.GetList<LogsItem>("logs");
List<Seating_chartItem> seatList = (from seat in seatCharts where seat.Room == 0 where seat.Floor == floor select seat).ToList();
List <UsersItem> usersList = (from user in users select user).ToList();
List <Excluded_usersItem> xusersList = (from xuser in exusers select xuser).ToList();
var results = from seat in seatList
join user in usersList on
seat.User_id equals user.User_id
where seat.Room == 0
where seat.Floor == floor
where !(from xuser in xusersList select xuser.User_id).Contains(user.User_id)
select new
{
sid = seat.Seat_id,
icon = seat.Icon,
topCoord = seat.Top_coord,
leftCoord = seat.Left_coord,
name = user.Name,
phone = user.Phone,
mobile = user.Mobile,
content = seat.Content
};
The time this code takes is frustrating, to say the least.
Thanks.
One immediate thing: You are re-querying xusersList everytime within your join:
where !(from xuser in xusersList select xuser.User_id).Contains(user.User_id)
Instead just first extract the user ids only (since that is the only thing you need)
var xusersList = (from xuser in exusers select xuser.User_id).ToList();
then use it directly:
where !xusersList.Contains(user.User_id)
Even better - determine the valid users before your query:
usersList = usersList.Where( user => !xusersList.Contains(user.User_id))
.ToList();
Now you can just completely remove this where condition from your query.
Also these where conditions seem to be unneeded:
where seat.Room == 0
where seat.Floor == floor
since you have filtered your seatList this way already.
Having said that you should log some performance data to see what actually takes the most time - is it acquiring the inital lists or your actual join/linq query?

Joining multiple one-to-many tables with Linq to SQL

Well I am trying to join 3 tables here is a brief summary of them
user - id,name,.....
contactdetails - id,detail,....,userId
adress - id,adress,.......contactdetailsId
how do I join these 3 tables with linq to sql?
Write something like (I can't read out the entire structure of the DB from your question):
var q = from a in ctx.address
select new {
a.address,
a.concactdetails.detail,
a.contactdetils.user.name
};
When having one-to-many relationships it's easiest to base the query on the table which "is most many". It is possible to do it the other way around and use LoadWith options. Unfortunately linq-to-sql only supports translating two tables into efficient querys when done that way. If you try it with three tables you will get a load of small fetch-one-line-queries hitting the DB dragging performance down terribly (see http://coding.abel.nu/2011/11/always-check-generated-sql/ for an example).
ContactDetail[] ContactDetails = new ContactDetail[0]; // your contact detail entries
Address[] Addresses = new Address[0]; // your address entries
User[] Users = new User[0]; // your user entries
Users.Join(ContactDetails, user => user.ID, cd => cd.ID, (user, cd) => new { User = user, ContactDetail = cd }).Join(Addresses, UserAndCD => UserAndCD.ContactDetail.ID, address=>address.ContactDetailID, (UserAndCD, address)=> new {User = UserAndCD.User, ContactDetail = UserAndCD.ContactDetail, Address = address});
In this case you will get user-contactdetail-address entries. If you want to get a user with contactdetail enumeration, and an address enumeration for each contactdetail, then you have to use GroupJoin:

Resources