Django: Getting Started Transcripts
Chapter: Posting Data
Lecture: Link to the user's reviews in the Django Admin

Login or purchase this course to watch this video and the rest of the course contents.
0:00 I want to add a column to the user listing that links to the users reviews. You've seen me do this before by adding a method to the admin object and
0:09 registering it in the list display attribute. I'm going to add a method called show reviews. So let me start by registering it.
0:21 As the base class already defines some things in the list display attribute. I'm just adding the new method,
0:27 registration here at the end of the existing one so I don't drop off the things that are already there.
0:46 This is the code that will output the column that references the reviews for the user. To do that, first off, you have to get all of the users reviews.
0:54 I do that by using the filter method on the reviews query manager.
0:59 Remember that this method will be called once for each row in the admin listing display with the ob argument containing the user being displayed.
1:07 I passed that obj into the filter filtering for reviews by this user. As I'm only interested in how many reviews there are.
1:15 I then change the filter with a call to count giving the number of reviews.
1:20 This is way faster than getting the length of the result as calling count will be
1:25 done in the database and only the number comes back rather than a whole query set
1:30 What I'm trying to output here is a link to the listing page for the review objects. To do that, I need a URL.
1:38 On line 21 I'm using the reverse call to look up the admin page for the review change list.
1:44 That's the listing of all review objects and I then pand a query parameter to filter just the reviews for this particular user.
1:54 On line 22, I'm determining whether or not the word review will need an S on the end.
2:00 And then finally on 24 I'm putting this all together to build the URL. The format HTML call will build a clickable URL
2:07 that is marked so Django doesn't escape it. I'm passing the URL I looked up with reverse the number of reviews and that pesky s to get the
2:16 plurals right. With the review admin model in place and the changes here to the user, I'm all set to go and add a review.
2:25 Oop I just noticed those angry little red lines underneath review, reverse and format HTML. They're telling me that I forgot to import them.
2:34 So let's go to the top of the file and fix that, all better.


Talk Python's Mastodon Michael Kennedy's Mastodon