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
Nick Scola
3,563 PointsAny suggestions on how to favorite a post?
I'm currently scratching my head over here trying to figure out a way to allow a user to favorite / star another user's post. I would assume we would need to grab the post ID and set some sort of relationship in models.py
1 Answer
Charles Lee
17,825 PointsOne way to implement a favorites feature is to create a Favorite model which would contain the user_id and post_id as foreign keys. Everytime a user favorites a post, we can create an instance of Favorite. If there is one that already exists with that exact user_id and post_id, we can destroy that instance, thereby 'unfavoriting' it.
This way allows you to make the resource RESTful and simply creating and destroying for 'favoriting' and 'unfavoriting.'
Nick Scola
3,563 PointsNick Scola
3,563 PointsThanks for your help! I was able to create this type of feature.
Charles Lee
17,825 PointsCharles Lee
17,825 PointsNo probs. Glad I could help. :D
Nick Scola
3,563 PointsNick Scola
3,563 PointsHey Charles, how come I'm getting this typerror: TypeError: argument of type 'SelectQuery' is not iterable
{% if not post.id in current_user.favorite() %}
Charles Lee
17,825 PointsCharles Lee
17,825 PointsHey Nick,
A guess would be that current_user.favorite() is returning something that the in operator will not work with. The in operator needs an iterable object.
Could you show me an example of what current_user.favorite() returns?
Nick Scola
3,563 PointsNick Scola
3,563 PointsThanks for the response. I'm actually confused on why favorite() is not iterable but following() is:
Charles Lee
17,825 PointsCharles Lee
17,825 PointsWell, I'm not entirely sure what's going on.
Maybe it's erroring out on an empty SelectQuery? Try out the exist() method. https://docs.djangoproject.com/en/1.8/ref/models/querysets/#django.db.models.query.QuerySet.exists
This also may be a related problem: http://stackoverflow.com/questions/6704749/relatedmanager-object-is-not-iterable-django
Nick Scola
3,563 PointsNick Scola
3,563 PointsAlso here's what returns when I call {{ current_user.favorite() }}
<class 'models.User'> SELECT "t1"."id", "t1"."username", "t1"."email", "t1"."password", "t1"."joined_at", "t1"."is_admin" FROM "user" AS t1 INNER JOIN "favorite" AS t2 ON ("t3"."id" = "t2"."to_user_post_id") WHERE ("t2"."from_user_fav_id" = ?) ORDER BY "t1"."joined_at" DESC [1]