Peksio
Peksio

Reputation: 585

Django - How to serialize (and later iterate through) list of dictionaries?

I am having hard time with serializing data from API since this is the first time that I am doing this. I would like to ask you for your help.

From API i receive dictionary with some keys. Value for key "Search" is list of dictionaries that I would like to print in a for loop in my template later. But I failed.

Here are my results that I managed to put together from few hours of googling and browsing through stack overflow.

Here is my views.py:

def results(request):
    title = request.POST.get("Title")
    api_key = "111111"
    url = f"http://www.omdbapi.com/?s={title}&type=movie&apikey={api_key}"
    response = requests.get(url)
    serializer = SearchListSerializer(data=response.json()["Search"], many=True)

    if serializer.is_valid():
        serializer.save()
        movies = serializer.objects.all()
    else:
        print(serializer.errors)
        print("Something went wrong.")
    return render(request, 'movie_database/results.html', movies)

And here is my serializers.py:

class MovieSerializer(serializers.ModelSerializer):

    class Meta:
        model = Movie
        fields = '__all__'


class SearchSerializer(serializers.DictField):

    Title = serializers.CharField(max_length=300)
    Year = serializers.CharField(max_length=100)


class SearchListSerializer(serializers.ListField):

    child = SearchSerializer()

I currently receive error:

TypeError at /results/
__init__() got an unexpected keyword argument 'data'

But I know that it is only a tip of the iceberg. And one of the problems.

Upvotes: 0

Views: 2112

Answers (0)

Related Questions