[Answer]-How to use models associated with a user in Django when rendering an HTML page

1👍

{{ request.user.taskitem_set.all }} would give you all the related task items. Now, to display it in your template:

{% for task_item in user.taskitem_set.all %}
    {{ task_item.task_n }}
{% endfor %}

would display the list of tasks.

Here is the documentation on reverse-queries on foreign key (related_name) Also, read this

0👍

you would do something like this:

{% for task in user.taskitem_set.all %}
    {{ task.task_n }}
{% endfor %}

This will fetch all TaskItem instances related to your user. (notice the extra database query)

While i don’t know how your view works, i will assume that you are making the right checks to make sure that every user can only see his own tasks.

One performance trick you will find most useful is to use prefetch_related(‘taskitem_set’), this will prefetch the TaskItem instances as long as your UserProfile instance with one query:

user = User.objects.filter(id=user_id).prefetch_related('taskitem_set')

You can tune the code to match your preferences.

Hope this helps!

Leave a comment