How to access columns after doing outerjoin in sqlalchemy - sqlalchemy

I did outerjoin of two tables. And I got the correct result. But I don't know how to access the Columns in the result. Below is my code.
result = db.session.query(Purchase, Product.pr_id).outerjoin(Product, Purchase.id == Product.pr_id).filter(Purchase.user_id==current_user.id, Product.status==pr_status).order_by(desc(Purchase.cost)).all()
'result[0].Purchase.cost' gives me cost of the first purchase. But 'result[0].Product.status' giving AttributeError: Could not locate column in row for column 'Product'.
Why this happen ? How can I access the 'status' column

Changing the second argument of db.session.query() from Product.pr_id to Product should work.
result = db.session.query(Purchase, Product).outerjoin(Product, Purchase.id == Product.pr_id).filter(Purchase.user_id==current_user.id, Product.status==pr_status).order_by(desc(Purchase.cost)).all()
This is in the docs at selecting-orm-entities-and-attributes] in the example with
stmt = select(User, Address).join(User.addresses).order_by(User.id, Address.id)

Related

Kaggle competition submission error : The value '' in the key column '' has already been defined

This is my first time participating in a kaggle competition and I'm having trouble submitting my result table. I made my model using gbm and made a prediction table like below. the submission file has 2 column named 'fullVisitorId' and 'PredictedLogRevenue') as any other kaggle competition cases.
pred_oob = predict(object = model_gbm, newdata = te_df, type = 'response')
mysub = data.frame(fullVisitorId = test$fullVisitorId, Pred = pred_oob)
mysub = mysub %>%
group_by(fullVisitorId) %>%
summarise(Predicted = sum(Pred))
submission = read.csv('sample_submission.csv')
mysub = submission %>%
left_join(mysub, by = 'fullVisitorId')
mysub$PredictedLogRevenue = NULL
names(mysub) = names(submission)
But when I try to submit the file, I got the 'fail' message saying ...
ERROR: The value '8.893887e+17' in the key column 'fullVisitorId' has already been defined (Line 549026, Column 1)
ERROR: The value '8.895317e+18' in the key column 'fullVisitorId' has already been defined (Line 549126, Column 1)
ERROR: The value '8.895317e+18' in the key column 'fullVisitorId' has already been defined (Line 549127, Column 1)
Not just 3 lines, but 8 more lines like this.
I have no idea what I did wrong. I also checked other kernels but couldn't find the answer. Please...help!!
This issue was because fullVisitorId was numeric instead of character, so It dropped all the leading zeros. Therefore, using read.csv() with colClases argument or fread() can make it work.
I left this just because there could be someone else who are having the similar trouble like me
For creating submission dataframe, the easiest way is this
subm_df = pd.read_csv('../input/sample_submission.csv')
subm_df['PredictedLogRevenue'] = <your prediction array>
subm_df.to_csv('Subm_1.csv', index=False)
Noe this is assuming your sample_submission.csv has all fullVisitorId, which it usually does in Kaggle. Following this, I have never faced any issues.

Laravel retrieving column value from query gives error

I am currently working on a school project and am trying to retrieve values from a successfully ran query. The query is as so:
$airportQuery = Airport::where('id', '=', $airport)->get(); //Returns all columns of users selected airportId
I am trying to retrieve a column "extendedcenterlineLong" and "extendedcenterlineLat". I am doing this by running
array[] = $airportQuery->extendedcenterLong;
array[] = $airportQuery->extendedcenterLat;
(The array isn't named array[] either) When I try to run myQuery I get this error
I have not been able to fix this issue, what am I doing wrong?
Many Thanks!
EDIT: I also have these queries to get the previous row or next row from waht the user selects
$previous = Airport::where('id', '<', $airport)->max('id'); //Returns the previous rows values from users current selected airportId
$next = Airport::where('id', '>', $airport)->min('id'); //Returns the next rows values from users current selected airportId
EDIT: I solved the problem by doing $airportQuery->first()->column_name. For some reason when I printed out $airportQuery there were two items that were arrays of the column info that were identical to each other, a copy basically.
You can just do a
$airportQuery = Airport::where('id', '=', $airport)->first();
i guess above should work.

Linq to EF not returning all data

I have following query against EF whereby mysql was used:
var query = from r in context.myContext
where r.clmn1.CompareTo("2015-11-19 00:00:00") > 0)
orderby r.someColumn
select r;
return query;
The number of returned rows is as expected. however some values of the property r.clmn2 repeat itself in the result of the query. For example I could not find clmn2 == 220011 because it was "overwritten" by the value 220033 (The value 220033 is correct and expected but should not "overwrite" other values). Strangely enough, when I add this condition to the query I get it in the result (of course then only and only this value) which means that the first condition is also valid for clmn2:
var query = from r in context.myContext
where r.clmn1.CompareTo("2015-11-19 00:00:00") > 0) && r.clmn2.Equals("220011")
orderby r.someColumn
select r;
return query;
The same query (the first one) works at DB-level and returns all values (will not be overwritten)
SELECT * FROM myContext.myTable
WHERE r.clmn1 > ("2015-11-19 00:00:00")
ORDER BY r.someColumn
It should be a problem of EF. I hope someone could help me!
Thanks in Advance.
I have prefixed the column/property clmn2 with [key] atribute in the generated entity class so that it is now a part of the multiple key, i.e., with other columns/properties. It works and i get all values from DB. Maybe cus this property comes from a DB-view, Visual Studio could not recognize it as a primary key as done by other properties.

Sum of a column in Webmatrix

I have searched for too many hours. Calculate TotalAmount from all Rows in Table was as close as I could find but could not get it to work.
I have a table called "ServiceEntered" and I need the SUM of the column "Price" to be displayed on the page. I have tried to change the field type in the table too but with no success.
I am using this code:
decimal money = 0.00m;
var prices = "SELECT SUM(Price) FROM ServiceEntered";
var db = Database.Open("OMD");
var result = db.QuerySingle(prices);
money = Convert.ToDecimal(result);
and have #money in the page.
It give me this error: Unable to cast object of type 'WebMatrix.Data.DynamicRecord' to type 'System.IConvertible'.
The SQL you are using is correct. However, the return type of the QuerySingle method is an object with properties generated dynamically from the database column(s) in your query. You have none - nor do you have any aliases for the expressions your SQL generates (the result of the SUM function). In fact, since you are only retrieving a scalar value from the database, you should use QueryValue instead. Try this:
var prices = "SELECT SUM(Price) FROM ServiceEntered";
var db = Database.Open("OMD");
var result = db.QueryValue(prices);
And then in your page you can use:
#result

LINQ sum returns wrong result

I have a table with rows containing the following numbers:
4191808.51
3035280.22
3437796.06
4013772.33
1740652.56
0
The sum of that table is 16419309.68.
When I do a Linq SUM query on that table, it returns a whole different number: 19876858.14
The code I use to do the sum is as follows:
IEnumerable<MyData> data = _myRepository.GetMatching(myValue);
decimal sumSales = data.Sum(x => x.Sales);
What could be causing this? I suspect some max decimal value but couldn't find info on that
can you please examine your
IEnumerable<MyData> data = _myRepository.GetMatching(myValue);
in the debugger after the execution. I'm suspecting that you are selecting some different set of data - not what you have shown in the sample. I attempted to recreated you situation LinqPad, but constantly getting the correct answer.
decimal[] data = {
4191808.51m
,3035280.22m
,3437796.06m
,4013772.33m
,1740652.56m
,0m
};
decimal sumSales = data.Sum();
sumSales.Dump();
and getting: 16419309.68