Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

Query from template in Django

I am coming from Ruby-on-Rail background. I have a user table and an employee table.

In the index page of all the employee, I am looking to retrieve their first name which is in the user model and not in the employee table.

I tried the following which is very rubyesque:

{% User.objects.filter(id=employee.user_id) %} 

But i get the error:

Invalid block tag on line 163: 'User.objects.filter(id=employee.user_id)', expected 'empty' or 'endfor'. Did you forget to register or load this tag?

Although the user_id clearly exists.

What is the best way for such queries in Django please ?

question from:https://stackoverflow.com/questions/65884074/query-from-template-in-django

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to add context in your view to access data in template like following:

def detail(request):
    # define employee 
    context = {'users': User.objects.filter(**filter_criteria)}
    return render(request, 'polls/detail.html', context=context)

then in your template you can use

{% for user in users %}
    <tr>
        <td>{{ user.name }}</td>
        <td>{{ user.email }}</td>
    </tr>
{% endfor %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...