compare two results (of many) from api data with django/python
Question: I'm learning django/python/css/etc... and while doing this, I've decided to
build an app for my website that can pull simple movie data from TMDb. What
I'm having trouble with is figuring out a way to add a way for the **user to
select two different movies, and once selected, see the differences between
them (run time, budget, etc).**

I've got grabbing the data from the API covered in that doing a search for a
movie on my site returns expected results. But now I'm having a really tough
time trying to figure out **how to select 1 item from the results to "save"
it, search again, select the second movie, and have the comparison show up.**

I know it's pretty vague, but any help getting me pointed in the right
direction would be greatly appreciated!

here's what I'm doing so far with the code:

views.py:

    
    
    from django.shortcuts import render
    from django.conf import settings
    
    from .forms import MovieSearch
    import tmdbsimple as tmdb
    
    tmdb.API_KEY = settings.TMDB_API_KEY
    
    
    def search_movie(request):
        """
        Search movie title and return 5 pages of results
        """
        parsed_data = {'results': []}
        if request.method == 'POST':
            form = MovieSearch(request.POST)
            if form.is_valid():
                search = tmdb.Search()
                query = form.cleaned_data['moviename']
                response = search.movie(query=query)
                for movie in response['results']:
                    parsed_data['results'].append(
                        {
                            'title': movie['title'],
                            'id': movie['id'],
                            'poster_path': movie['poster_path'],
                            'release_date': movie['release_date'][:-6],
                            'popularity': movie['popularity'],
                            'overview': movie['overview']
                        }
                    )
                for i in range(2, 5 + 1):
                    response = search.movie(query=query, page=i)
                    for movie in response['results']:
                        parsed_data['results'].append(
                            {
                                'title': movie['title'],
                                'id': movie['id'],
                                'poster_path': movie['poster_path'],
                                'release_date': movie['release_date'][:-6],
                                'popularity': movie['popularity'],
                                'overview': movie['overview']
                            }
                        )
                context = {
                    "form": form,
                    "parsed_data": parsed_data
                }
                return render(request, './moviecompare/movies.html', context)
            else:
                form = MovieSearch()
        else:
            form = MovieSearch()
    
        return render(request, './moviecompare/compare.html', {"form": form})
    
    
    def get_movie(request, movid):
        """
        from search/movie results, get details by movie id (movid)
        """
        movie = tmdb.Movies(movid)
        response = movie.info()
        context = {
            'response': response
        }
        return render(request, './moviecompare/detail.html', context)
    

movies.html:

    
    
    {% extends 'moviecompare/compare.html' %}
    
    {% block movies_returned %}
    <div class="wrap">
    <div class="compare-gallery">
    
    {% for key in parsed_data.results|dictsortreversed:'release_date' %}
    {% if key.poster_path and key.release_date and key.title and key.overview %}
        <div class="gallery-item">
            <img src="http://image.tmdb.org/t/p/w185/{{ key.poster_path }}">
       <div class="gallery-text">
           <div class="gallery-date"><h5><span><i class="material-icons">date_range</i></span> {{ key.release_date }}</h5></div>
            <div class="gallery-title"><h3><a href="{% url 'compare:movie_detail' movid=key.id %}">{{ key.title }}</a></h3></div>
           <div class="gallery-overview">{{ key.overview|truncatechars:80 }}</div>
           </div>
        </div>
    {% endif %}
    {% endfor %}
    </div>
    </div>
    {% endblock %}
    

and I've got a simple detail.html that doesn't do anything just yet, but it's
just for showing detail results for a single movie, so not important to get
into yet as it'll just be styling.

I'd like for each result in the gallery to have a link to a details page for
the movie(done), and also a select box (or similar) to select it as one of the
comparison movies.

If I can just get some help on how to select two different movies from the
search results, and compare those, I think I could work out a way to do the
same with two separate movie searches. Thanks for any help!

edit: here's what I have so far on
[pythonanywhere](http://moniblog.pythonanywhere.com/compare/) \-


Answer: Assuming you want to be able to add movies from different searches (e.g.
search for rambo, add rambo, search for south park, add south park), you can
probably do something like:

    
    
    @require_POST
    def save_compare(request, pk):
         """ Async endpoint to add movies to comparison list """
         movies = request.session.get('comparing_moviews', [])
         movies.append(movies)
    
         # if you only need the data the API served originally, you could also save that to a data-base when you read it from the API and use it here
         request.session['comparing_movies'] = movies
         return JsonResponse("")
    
    def show_comparison(request):
         """ show differing stats like "1 hour 3 mins longer """
         mov1, mov2 = request.session.get('comparing_movies')  # need to handle wrong number of selected
    
         # not sure from the description how to look up the movies by id
         mov1 = tmdb.Search().search(pk=mov1)
         mov2 = tmdb.Search().search(pk=mov2)
    
         return render_to_response("comparison.html", context={
              "mov1": mov1, "mov2": mov2, 
              "length_diff": mov1['length'] - mov2['length']})
    

to give you the comparison stats you want. You'll also need [session
middleware](https://docs.djangoproject.com/en/1.10/topics/http/sessions/)
installed.

From the search results page, you'll add a button that triggers an async js
post to `save_compare` which starts accumulating a comparison list. When
they're done, they can click "compare" or something on that list, which will
render "comparison.html" with the two movies and the diff however you like it.

As an example of some calculation for your "comparison.html", you can grab the
hours and minutes from the `length_diff` and render them as "X hours and y
minutes longer."

