how to combine order_by and filter_by in sqlalchemy using flask - flask-sqlalchemy

I want to call a query by filter_by and order_by them by using a column of the filtered data. Pls tell how do I achieve so.
current_blog_post_replies = current_blog_post_reply.filter_by(blog_reply = blog_post_id)
Now i want to order_by this query by a column called time. Pls tell how to do so?

I am supposing your table class is named CurrentBlogPostReply.
Use this query
current_blog_post_replies = CurrentBlogPostReply.query.filter(CurrentBlogPostReply.blog_reply == blog_post_id).order_by(CurrentBlogPostReply.time).all()

Related

UPDATE QUERY - Sum up a value from form with value from table

I've just started using microsoft access so I don't really know how to solve this. I would like to use an update query to add a value from a form to a value on a table.
I originally used the SUM expression which gave me an error saying it was an aggregate function.
I also tried to add the two values together (e.g [field1] + [field2]) which as a result gave me a value with both numbers together instead of adding them together.
The following is the SQL I'm using:
UPDATE Votes
SET Votes.NumVotes = [Votes]![NumVotes]+[Forms]![frmVote]![txtnumvotes]
WHERE (((Votes.ActID) = [Forms]![frmVote]![combacts])
AND ((Votes.RoundNum) = [Forms]![frmVote]![combrndnum]))
I want to add a value [txtnumvotes] a form to a field [NumVotes] from the table [Votes].
Could someone please help me?
You can specify the expected data type with parameters:
PARAMETERS
[Forms]![frmVote]![txtnumvotes] Short,
[Forms]![frmVote]![combacts] Long,
[Forms]![frmVote]![combrndnum] Long;
UPDATE
Votes
SET
Votes.NumVotes = [Votes]![NumVotes]+[Forms]![frmVote]![txtnumvotes]
WHERE
(((Votes.ActID) = [Forms]![frmVote]![combacts])
AND
((Votes.RoundNum) = [Forms]![frmVote]![combrndnum]))
Without the specification, Access has to guess, and that sometimes fails.

using .where with .find

I am wondering how I can use where cause with the ActiveRecord find method.
Here is the code I am using:
Supplier.joins(:products).find(params[:id]).where('suppliers.permalink = ? AND variants.master = ?', params[:id], TRUE)
which gives me:
undefined method `where' for #<Supplier:0x007fe49b4eb330>
Supplier.joins(:products).find(params[:id]).where('suppliers.permalink = ? AND variants.master = ?', params[:id], TRUE)
What you're doing here is finding the first record with the id contained in params[:id], then trying to run a where statement on that single record. where only works when run against the model itself.
The confusing part here is that you are using params[:id] both for the primary key (find searches the id field) but then also comparing it to the permalink column in the where clause.
To explain the usage of both methods:
find will search for result(s) from the table, matching the argument you provide it to the id field. You can pass in multiple id's and this method is mostly used to select a row that you know exists, by id. Most commonly it is used with a single id and returns a single instance.
where is used to find all results from the table that match the clause and return a collection of records. You can then refine these results or select one, for example by using .first:
Supplier.joins(:products).where('suppliers.permalink = ? AND variants.master = ?', params[:permalink], true).first
(Note that you're using joins(:products) but then querying variants table. Is this incorrect?)
Supplier.joins(:products).where('suppliers.permalink = ? AND variants.master = ?', params[:id], TRUE).find(params[:id])

'Where' Query in Rails

I have a table Order(:id, :number). I need to find count of those records from Order whose column(:number) value is not -1(default). I wrote :
Order.where(:number != -1).count
But this gives the value Order.count still. What is wrong?
You don't pass arguments to where properly. In this case, you should pass it as string:
Order.where('numer != ?', -1).count
or use not:
Order.where.not(number: -1).count

Need help converting SQL query to Ruby.

I'm new to Ruby on Rails. I'm trying to determine the proper ruby query for the following SQL query.
Select max(bid_amount) from biddings where listing_id = 1;
I need to extract the maximum value in the bid_amount column. But it has to have a dynamic listing_id.
Try:
Bidding.where('listing_id = :listing_id', listing_id: 1).maximum(:bid_amount)
Update:
To follow up on your comment: since you say you are passing in params[:id], it's best to convert that parameter to integer so that unwanted values don't go to the database. For e.g.
Bidding.where('listing_id = :listing_id', listing_id: params[:id].to_i).maximum(:bid_amount)

Django select only rows with duplicate field values

suppose we have a model in django defined as follows:
class Literal:
name = models.CharField(...)
...
Name field is not unique, and thus can have duplicate values. I need to accomplish the following task:
Select all rows from the model that have at least one duplicate value of the name field.
I know how to do it using plain SQL (may be not the best solution):
select * from literal where name IN (
select name from literal group by name having count((name)) > 1
);
So, is it possible to select this using django ORM? Or better SQL solution?
Try:
from django.db.models import Count
Literal.objects.values('name')
.annotate(Count('id'))
.order_by()
.filter(id__count__gt=1)
This is as close as you can get with Django. The problem is that this will return a ValuesQuerySet with only name and count. However, you can then use this to construct a regular QuerySet by feeding it back into another query:
dupes = Literal.objects.values('name')
.annotate(Count('id'))
.order_by()
.filter(id__count__gt=1)
Literal.objects.filter(name__in=[item['name'] for item in dupes])
This was rejected as an edit. So here it is as a better answer
dups = (
Literal.objects.values('name')
.annotate(count=Count('id'))
.values('name')
.order_by()
.filter(count__gt=1)
)
This will return a ValuesQuerySet with all of the duplicate names. However, you can then use this to construct a regular QuerySet by feeding it back into another query. The django ORM is smart enough to combine these into a single query:
Literal.objects.filter(name__in=dups)
The extra call to .values('name') after the annotate call looks a little strange. Without this, the subquery fails. The extra values tricks the ORM into only selecting the name column for the subquery.
try using aggregation
Literal.objects.values('name').annotate(name_count=Count('name')).exclude(name_count=1)
In case you use PostgreSQL, you can do something like this:
from django.contrib.postgres.aggregates import ArrayAgg
from django.db.models import Func, Value
duplicate_ids = (Literal.objects.values('name')
.annotate(ids=ArrayAgg('id'))
.annotate(c=Func('ids', Value(1), function='array_length'))
.filter(c__gt=1)
.annotate(ids=Func('ids', function='unnest'))
.values_list('ids', flat=True))
It results in this rather simple SQL query:
SELECT unnest(ARRAY_AGG("app_literal"."id")) AS "ids"
FROM "app_literal"
GROUP BY "app_literal"."name"
HAVING array_length(ARRAY_AGG("app_literal"."id"), 1) > 1
Ok, so for some reason none of the above worked for, it always returned <MultilingualQuerySet []>. I use the following, much easier to understand but not so elegant solution:
dupes = []
uniques = []
dupes_query = MyModel.objects.values_list('field', flat=True)
for dupe in set(dupes_query):
if not dupe in uniques:
uniques.append(dupe)
else:
dupes.append(dupe)
print(set(dupes))
If you want to result only names list but not objects, you can use the following query
repeated_names = Literal.objects.values('name').annotate(Count('id')).order_by().filter(id__count__gt=1).values_list('name', flat='true')