Issues with Fetching the data from database - django

I can fetch the data like this.
value= mymodel.objects.get(anycondition)
OR
value= mymodel.objects.filter(anycondition)
and can send them to my template with context.
But if I want to select all the data from a table(for all users not only one) as this query does
value= mymodel.objects.all()
and send this value to my template and can see there field by field
e.g.
my table has two fields name and phone no and I use the above query( value= mymodel.objects.all()) now if i want to see all names then i can see that and if i want to see phone no. I can see that too.
I have tried this and it doesn't work and I even I do not know it is possible or not.
If it is possible then please let me know how I can do this ?
I hope you understand my question. !!
Thanks in advance

.all() will return a list of objects that represent the rows in your model. .get() only returns one object. Your template is trying to print the result of all() if it was one object.
This is the same as if you had a list and you wanted to loop through it. In your view you would do:
product = Product_attributes.objects.all()
for i in product:
print i.size
print i.color
The equvalent for the template is:
<ul>
{% for i in product %}
<li>{{ i.size }}</li>
<li>{{ i.color }}</li>
{% endfor %}
</ul>

Although this question isn't clear it seems like you are having a bit of problem with Field Lookups. It is fairly easy to learn Here is a link to get you started

Related

Length of list in jinja template, where the list is the result of a DBSession.query

How do I find the length of a list of objects in a jinja template when the list of objects has been created by querying a database?
I thought There are {{ items|length }} items in this category. would work, but items is a result of:
items = db_session.query(Item).filter_by(category_id=category.id)
and I get the error
TypeError: object of type 'Query' has no len()
Obviously, I could calculate the length separately and pass into render_template(), but I wondered if there was a better way?
Any help from the community would be much appreciated :)
items object is not a list yet, it is an unprocessed Query object as you see in the error. You can use Query.all() method to get a list of items:
items = db_session.query(Item).filter_by(category_id=category.id).all()
After that length filter can be applicable.
Use {{ items | count }} in jinja template
Try to add loopcontrol extension
app.jinja_env.add_extension('jinja2.ext.loopcontrols')
Then
{% for item in items %}
{{loop.length}}
{% break %}
{% endfor %}

How to create 2D list of a database table and evaluate it in a template?

I've got a model class, House, with several columns. I want to get all the entries to this table, with all the columns, and display these on in a table in a template.
Firstly, how do I pull all the information that I need out of the database (and into a 2d list?), and what tag could I use to access specific data in the table?
it's as easy as stated here
so, practically:
all_houses = Houses.objects.all()
will give you all the entries in your database.
from within a view, pass that variable to the template context then, in the template:
{% for house in all_houses %}
{{ house.<column_name> }}
{% endfor %}
let me explain this bit of code: once you pass all your entries to the template, you can loop them with {% for %}
{{ house. }} means that you can extract the value you need from the column you need ( column_name ) and place it wherever you want (from whitin the for loop, obviously) so you can have (for example) {{ house.price }}, {{ house.bathrooms }} and so on, for each entry you have in your "all_entries"

Ordered list not working in Django

Im trying to using a ordered list in HTML to list the items in my querylist for some reason the ordering is not happening..
The list is diplayed but not ordering.
Here is my Django code,
<o1>
{% for t in teamrel %}
<li> {{t.teamrelation}} </li>
{% endfor %}
</o1>
Here is my output in the HTML code,
Patron Relations Team Volunteer Relations Team Volunteer Relations Team
its not getting ordered.
Let me know your inputs.
The main problem is that your code sample appears to have an <o1> tag (o+ONE) instead of <ol> (o+L).
Probably because <o1> shoudl be <ol>.
Otherwise, the QuerySet needs to be ordered correctly with an queryset.order_by('foo') call. Regardless of invalid tags, the output should be ordered.
You can print print queryset.query to see the actual ordering asked of the database.

Django: Return all Values even if filtering through a related model

Thanks to some fantastic help on a previous question I have managed to put together my query. Everything works swimmingly save one issue.
careers = Career.objects.filter(job__dwarf__user = 1).annotate(dwarves_in_career = Count('job__dwarf'))
In my view this does exactly what I want and when I loop it in my template like so:
{% for career in careers reversed %}
<li>{{ career.name }}: {{ career.dwarves_in_career }}</li>
{% endfor %}
I get what I expected. My issue is that the above code will only return the Careers that have dwarves. I need it to return all careers:
Unassigned: 1
Construction: 1
Crafting: 2
Gathering: 0
Farming: 0
is my expected results. Instead the last two rows are not there because I am filtering for the specific user. I know why it's happening, what I am trying to figure out is how to get the query to return all careers, even if their dwarf count for a particular user is 0.
I think you need to swap over your annotate and filter clauses. See the documentation on this - the way you have it, it filters the queryset, but you actually want to keep the entire queryset but just filter the annotations.
So, I eventually figured it out...
from django.db.models import Count, Q
def fortress(request):
careers = Career.objects.filter(Q(job__dwarf__user = 1) | Q(job__dwarf__user__isnull = True)).annotate(dwarves_in_career = Count('job__dwarf'))
return render_to_response('ragna_base/fortress.html', {'careers': careers})
Not exactly sure what Q is but it works!
More information here: http://www.djangoproject.com/documentation/models/or_lookups/
Basically what I am doing is finding all careers with dwarves (based on user_id) OR all careers that have no dwarves (based on null)

Modifying QuerySet result

Is it possible to change some specific items in a QuerySet object? In my case i'm trying to slicing "title" fields with length more than 40 characters and append "..." at the end of field.
There are 2 ways of doing what you want.
The first is to use a Django filter. So if you are looping through the items of your queryset and displaying them on a page use something like truncatewords. You would use this like this in your template:
{% for item in queryset %}
<h1>{{ item.title|truncatewords:3 }}</h1>
{% endfor %}
It doesn't look like there is a Django filter for truncating base on the number of characters. If you want to write your own filter it's not that hard to do.
The other option is to put a method on your model to do what you want. Here is an example:
#property
def short_title(self):
return '%s...' % self.title[:40]
You would then be able to reference this anywhere in your template as {{ object.short_title }}.
I suggest adding a new property 'adjusted_title' to each object
for item in your_query_set:
if(len(item.title) > 40):
item.adjusted_title = item.title[0:40] + "..."