Как вернуть экземпляр django ibject клиенту через ajax

Я пытаюсь использовать асинхронный (ajax) возврат экземпляра модели Django на стороне клиента. Что-то не имеет смысла с разбором объекта в json / dict туда и обратно, я полагаю.

# views.py

def get_offer_details(request):
    """
    View to get the queried club's data
    """

    # Get the passed club name
    club_name = request.POST.get('club_name')

    # Query the club object
    club_obj = Club.objects.get(name=club_name)

    # Transform model instance to dict
    dict_obj = model_to_dict(club_obj)

    # Serialize the dict
    serialized_obj = json.dumps(str(dict_obj))

    # Return object to client
    return JsonResponse({'club_obj': serialized_obj}, safe=False)

# .js

function get_offer_details(club_name) {

    $.ajax({
        url : "/get-offer-details/", // the endpoint
            headers: {'X-CSRFToken': csrftoken}, // add csrf token
            type : "POST", // http method
            data : { club_name : club_name }, // data sent with the post request

            // Update client side
            success : function(data) {

                // Grab the returned object
                let obj = data.club_obj

                // Parse it into an object
                let parsed_obj = JSON.parse(obj) // console.log(typeof) returns "string"

                // Access the data of the object
                let prev_goals = obj.goals_last_season // console.log(prev_goals) returns undefined

...
console.log(data.obj)

--> {'id': 2, 'name': 'FC Bayern Munich', 'logo': <ImageFieldFile: images/fcb_logo.png>, 'goals_last_season': 79, 'points_last_season': 71}

Вернуться на верх