SQLalchemy: iterate through raw SQL query in template - flask

Have a code in function, which renders ResultProxy (as I understand), to template, like this:
query = db_session.execute(serious_business_query) #raw sql
return render_template('result.html', query=query)
I want to iterate through it in my template, but see nothing. How can I iterate through ResultProxy object? Or what should I pass to template to simply iterate through it?
Links to docs are OK, cant find what I need.

You might want to try this suggestion https://stackoverflow.com/a/17987782/1307985
and when you fill in a list from the cursor then to pass it to the template.
I am guessing, but probably the jinja2 template does not know how to itterate over cursor or query like object so it have to be converted to a list object.

Related

Ember/Handlebars: Localization Helper with parameter array

I want to localize a string that contains multiple placeholders.
E.g:
Hello %#1, today is %#2
I'd like to pass an array to the localization helper in my template like so:
{{loc "greetings" myArray}}
But that doesn't work, even though the documentation says it should.
What does work is
{{loc "greetings" "John" "Monday"}}
But the data I receive to display is an array and I don't want to store each element in a seperate variable.
How can I get the loc helper in the template to work with an array of data? Am I doing something wrong?
For the people how will fall here :
He gets his answer here : https://github.com/emberjs/ember.js/issues/16337
Loc should be/will be/is deprecated

django queryset ordering

I'm listing queryset results and would like to add an option for choosing the order results are displayed.
I would like to pass the actual data from the database to other page for sorting.
I was able to achieve such thing by getting all objects ids and use django session to recreate a new queryset based on the order criteria.
I was thinking if there is any other way to achieve such goal?
10x
Assuming you are currently displaying the data as a table, you could give chance to some javascript client side table sorter such as tablesorter. There are lots of javascript table sorte.
I'm away from my development machine right now, but I think you could just pass the list of ids to a new Queryset, pk__in=list_of_object_ids, and then use the native order_by function.
For example:
objs = Object.objects.filter(pk__in=list_of_object_ids).order_by('value_to_order_by')
Anyway, that's what I would try first, though I'm sure there are better optimizations.
For example, instead of a list of object ids, you could pass a dictionary with a key:value pair that has the value you want to order by.
For example:
[{'obj_id':1,'obj_value':'foo'},{'obj_id':2,'obj_value':'foo'}]
Then use some lambda function to sort it, like here.

Django: Find element in list by value

I have a sorted list of objects that I want my users to select a range from. For this I added two select elements (called from and to)to my web page. from is filled directly from the list, like this:
<select id="from">
{% for el in el_list %}<option>{{el.number}}</option>{% endfor %}
</select>
Once a value has been selected in from I'd like to populate to with the values from the selected value until the last one.
The list is sorted by the number attribute on python's side so I guess all I need to do is find the selected element in the list, slice the list accordingly and use the rest to populate my second select.
I've searched the documentation and several snippets but so far I've only found filters giving me the last or the first element of a list. I also know I can check if the selected value is in my list using in, but how can I then get that object's index?
I know I could probably run along the whole list with a for ... if, but I am almost sure there's a more elegant method out there, that I simply haven't found yet.
If any of you could provide me with a few pointers on how to solve this more elegantly it'd be much appreciated.
I don't know why you're looking through template tags for this. They won't help: by the time the user sees the page to select something from the from select, the template has already been rendered. You need to use Javascript.

Is it a good idea to modify fields in Model instances returned in a QuerySet? Will it kill performance?

So, my problem is this. I have a legacy MySQL database that I'm building a shiny new Django application over. For whatever reason, some fairly daft design decisions were made—such as all fields, no matter what they contain, being stored as varchars—but because since other systems that I'm not rewriting depend on that same data I can't destructively change that schema at all.
I want to treat a certain field—the stock quantity on hand—as an integer, so that in my template I can check its amount and display a relevant value (basically, if there are more than 100 items available, I want to just display "100+ Available").
The existing value for stock quantity is stored as, oddly, a varchar holding a float (as if it's possible to have fractional amounts of an item in stock):
item.qty: u"72.0"
Now, I figure as a worst case I can use QuerySet.values(), and iterate over the results, replacing each stock quantity with an int() parsed version of itself. Something like ...
item_list = items.values()
for item in item_list:
item['qty'] = int(float(item['qty']))
... but won't that cause my QuerySet to evaluate itself completely? I confess to being fairly ignorant of the process by which Django handles lazy execution of queries, but it seems like working with actual values would mean evaluating the query before it needs to.
So, am I complaining about nothing (I mean, it's definitely evaluating these values in the template anyway), or is there a better way to do what I need to do?
Yes, iterating through in the view would evaluate the entire queryset. That may or not be what you want - for example, if you're paginating, the paginator limits the query automatically, so you don't want to evaluate the whole thing separately.
I would approach this in a different way, by calling a function in the template to format the data. You can either do this with a method on the model, if there's just one field you want to format:
class Item(models.Model):
...
def get_formatted_qty(self):
return int(float(self.qty))
and call it:
{{ item.get_formatted_qty }}
Or, to make it more general, you can define a custom filter in your templatetags:
#register.filter
def format_value(value):
return int(float(value))
{{ item.qty|format }}

In django, can one use F() objects to see if a constant contains strings from a field?

All,
I'm trying to basically do keyword notifications, so whenever an object with a name is created, anyone who wants to be notified of any of the words in this name will be.
e.g.
Records:
keyword: Hello
keyword: World
New Name: "Hello World"
Returns both records
I've created a query that correctly works for this in sqlite, and I know how to translate it across databases.
SELECT * FROM table t
WHERE "a constant string" LIKE "%" || t.field || "%";
I've determined that within django, one can use F() objects to compare one field to another field, like so:
Entry.objects.filter(n_comments__gt=F('n_pingbacks'))
Now anyone know how to replace the first field with a constant string? Like so:
Entry.objects.filter("constant string"__icontains=F('n_pingbacks'))
Or am I going about this backwards?
It doesn't look particularly pretty but it can be done all with standard filters.
from django.db.models import ExpressionWrapper, CharField, Value
Entry.objects.annotate(
my_const=ExpressionWrapper(Value("a constant string"),
output_field=CharField())
).filter(my_const__contains=F('n_pingbacks'))
You can do this by providing a dict of arguments, e.g.:
Entry.objects.filter(**{("%s__icontains" % constant_string):F('n_pingbacks')})
Try using '.extra' to select your const as field, than using myconst__contains, like:
queryset.extra(select={'myconst': "'this superstring is myconst value'"}).filter(myconst__contains=F('myfield'))
Do not forget to put constant value in apostrophes inside double qoutation marks.
But, will somebody help me put it into Q object? =)
UPD:
Suddenly, it fails because of the following issue:
https://code.djangoproject.com/ticket/13363
Maybe, they will fix it.
UPD: You can filter by fields that added with '.annotate', but I don't know, how to put constant here instead of aggregation. Maybe, with creation of custom aggreation function, like here:
http://coder.cl/2011/09/custom-aggregates-on-django/
UPD: I made custom aggregator, this logic seems to be correct, because the query I got from queryset is quite similar to I wanted it to be, but, unfortunately, there is another issue: 16731 (sorry not providing full url, not enough rep, see another ticket above).
UPD(last): I have managed to do this using monkeypatching of the following:
django.db.models.sql.Query.query_terms
django.db.models.fields.Field.get_prep_lookup
django.db.models.fields.Field.get_db_prep_lookup
django.db.models.sql.where.WhereNode.make_atom
Just defined custom lookup 'starts', which has reverse logic of 'startswith'
You should not try to fight with django ORM. It covers the most often things but your case is not the one. Just use extra to get what you need (or even raw).