Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Why do we need to pass in primary keys into our views and our urls? When do we generally need to pass in primary keys?

Thank you advance for the help?

The motivation for my question is making sure I understand when to pass in primary keys.

Example in views.py

def step_detail(request, course_pk, step_pk):
    step = get_object_or_404(Step, course_id=course_pk, pk=step_pk)
    return render(request, 'courses/step_detail.html', {'step':step})

Example in step_detail.html

<a href="{% url 'courses:detail' pk=step.course.pk %}

Note 1) I get what primary keys are. They're like addresses. They are automatically generated ids. This was a good explanation imo https://www.essentialsql.com/what-is-the-difference-between-a-primary-key-and-a-foreign-key/

Note 2) I've looked through the following resources: https://teamtreehouse.com/community/whats-up-with-pks-django-course-views https://teamtreehouse.com/community/help-me-understand-ppk https://teamtreehouse.com/community/whats-the-correct-way-to-handle-bad-pks https://teamtreehouse.com/community/how-does-the-value-of-pk-the-named-regex-get-passed-to-viewscoursedetails

1 Answer

Samuel Ferree
Samuel Ferree
31,722 Points

If you're view is showing a specific piece of data, you should pass the primary key so your controller knows how to load that piece of data.

If you're view is showing a list of data (like a search view) then you're probably passing in search criteria, instead of a pk.