I have a model:
class ProjectBookmark(models.Model):
user = models.ForeignKey(User)
project = models.ForeignKey('Project')
say a user is viewing a project, is there a way to somehow check if current project is in users bookmarks other than a nasty way I do this now via request context as bellow? Basically, users bookmarks are a list of projects and checked as
{% if current_project in current_user.bookmarks %}…
right from inside the template?
the_user = request.user
bookmarked_projects = list()
for b in ProjectBookmark.objects.filter(user = request.user):
bookmarked_projects.append(b.project_id)
the_user.bookmarks = Project.objects.filter(id__in=bookmarked_projects)
return {'current_user':request.user}
For use directly in a template, the best way to go would be creating a custom template tag. Check out the template tag docs.
As for the filtering code itself, it would be very helpful to provide
related_namearguments to theForeignKeyfields in the model definition. For example:This way you could access a
QuerySetobject containing all the users bookmarks usingrequest.user.project_bookmarks.all()