Querying a single field within a Jinja2 template - flask

I'm working on an application where users can enter work requests, and subsequently go in and search for requests. The issue I'm having is building out the request summary screen. Basically, it lists the results of a search query. The snippet from the template is as such:
{% for req in workrequests %}
{{ req.id }} {{ req.customer }} {{ req.dateEntered }} {{ req.Contact }}
{% endfor %}
Here's wher I get hung up. The req.customer, and req.Contact fields are just keys for the customer and contact databases. I want to display the customer name and contact name. I assume the following queries should do the trick:
Customer.query.filter_by(req.customer).one()
Contact.query.filter_by(req.Contact).one()
Problem is, that will return the entire record. I'm just after the name field from both of those tables to put into my template, which is where the problem is. I'm not sure how to proceed with this

Customer.query is a short form of db.session.query(Customer). Use the latter to query for specific columns:
db.session.query(Customer.name).filter_by(id=req.customer).one()
Although I think that what you really want is a single query that gets all the data at once. Something like:
db.session.query(
WorkRequest.id,
WorkRequest.dateEntered,
Customer.name,
Contact.name
).join(
Customer,
Contact
).filter(...)

Related

How do I get data from a query datasource field in Sitecore using Scriban?

I have a query datasource field, and I want to access the data from within that field.
I have tried things like:
{{ for i_data in (sc_query i_page 'query:{{ i_page.NameOfField }}') }}
<h1>{{ i_data.Title }}</h1>
{{end}}
and
<h1>{{ i_data.NameOfField.Title }}</h1>
For the first example, I have also tried 'query:'{{ i_page.NameOfField }}. I have copied and pasted the query to make sure it is valid, and it is. It works. Am I getting some syntax wrong, or is there another way of doing this?

Best way to slice a Django queryset without hitting the database more than once

I'm running a query to get the 5 latest News items. In my template, I want to display the first item in one location, then the remaining 4 further down the page.
In my template, I do something like this:
{% for n in news|slice:":1" %}
{{ n.headline }}
{% endfor %}
... more HTML ...
{% for n in news|slice:"1:" %}
{{ n.headline }}
{% endfor %}
When I look in the Debug Toolbar, this results in two queries to the database: one with LIMIT 1 and another with LIMIT 4 OFFSET 1, but otherwise the same. I appreciate this is Django's way of intelligently only requesting the stuff you actually use, but in this case it seems a little excessive. What's the best way to do this kind of thing?
Convert to a sequence in the view, then slice the sequence.
var = list(somequery[:5])
You just need to force the queryset to evaluate itself before the slice. This could be done as simply as calling len() on it in your view before passing it off to the context.
The Django docs have a complete list of everything that causes a queryset to evaluate. Just do something from that list and you're good.

Django Custom Template Tag with Context Variable Argument

I have a custom template tag which shows a calendar. I want to populate certain items on the calendar based on a dynamic value.
Here's the tag:
#register.inclusion_tag("website/_calendar.html")
def calendar_table(post):
post=int(post)
imp=IMP.objects.filter(post__pk=post)
if imp:
...do stuff
In my template, it works fine when I pass a hard coded value, such as
{% load inclusion_tags %}
{% calendar_table "6" %}
However when I try something like {% calendar_table "{{post.id}}" %} , it raises a error a ValueError for the int() attempt. How can I get around this?
You want {% calendar_table post.id %}; the extra {{ and }} are what are causing you the heartburn.
Note that, in your custom tag, you need to take the string ("post.id") that gets passed and resolve it against the context using Variable.resolve. There's more information on that in the Django docs; in particular, look here: http://docs.djangoproject.com/en/1.3/howto/custom-template-tags/#passing-template-variables-to-the-tag

Can a django template be referenced from within a loop on another template?

I have a django template which loops over many notes/comments. As a simplified example take this.
{% for note in notes %}
<p>
Date added: {{ note.date_added }}
{{ note.note|urlize|url_target_blank|linebreaks }}
</p>
{% endfor %}
Then on the same page I have a form to add a new note. This note form is an ajax form and returns the newly submitted note back to the page and appends it at the end of the already existent note area.
I don't like this because I have to maintain the same html structure both in the page for the initial load, as well as in the response from the ajax form.
Is there a way to put a call to another template, inside of a template (in this for loop) so I can maintain the note formatting in one location only?
Thanks.
Perhaps you're looking for the "include" tag: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#include

Django template: Ordering dictionary items for display

I am making a website that displays a user's chosen youtube videos. A user can enter a comment for each video.
I want to display (in this order):
User comment
video title
I have already made the view and have created the following list of dictionary items. Each one represents one video. I send this to my html page:
[
{"my_own_object": vid_obj1, "youtube_obj": obj1}
{"my_own_object": vid_obj2, "youtube_obj": obj2}
]
"youtube_obj" is the object supplied by youtube, which contains the url, title, rating, etc. "my_own_object" contains the user's comments as well as other information.
I iterate over the list and get one dictionary/video. That's fine. Then I need to display the video's information:
{% for key,value in list.items %}
{% if key = "my_own_object" %}
<div>
<p>{{value.user_comment}}</p>
</div>
{% endif %}
{% if key = "youtube_obj" %}
<div>
<p> {{value.media.title.text}}</p>
</div>
{% endif %}
{% endfor %}
This works, except that, because I cannot determine the dictionary order, I might end up with:
Video title
User comment
I thought I could get around this by assigning variables (and then printing the values in the proper order), and am still reeling from the fact that I cannot assign variables!
So, how can I get around this? Can I pluck the key/value that I need instead of iterating over the dictionary items - I tried looking for ways to do this, but no luck. Any other ideas? (I need to pass both video objects as I may need more information than comment and title, later.)
You can use dictionary keys directly:
{% for item in list %} {# PS: don't use list as a variable name #}
<p>{{item.my_own_object.user_comment}}</p>
<p>{{item.youtube_obj.media.title.text}}</p>
{% endfor %}
Just iterate twice. Once for the videos, and once again for the comments. Or, split them into their own dictionaries that are passed through to the template. That's probably a better option, as you avoid iterating twice over the dict. For very small dicts this will be no problem. For larger ones, it can be a problem.