如何在DRF中发布请求后将模型对象作为json返回?

时间:2017-08-06 20:42:58

标签: python json django django-models django-rest-framework

在我的django rest api中,我有一个视图,通过创建一个新的Debt模型实例并保存它来增加债务。如果此操作成功,则api应返回包含新创建的Debt模型实例的响应为json。负责增加债务并返还债务的模型中的函数是:

def add_debt(self, from_user, to_user,
            paying_user, receiving_user,
            amount, currency, description, 
            date_incurred, deadline, payed, overdue):
    """ Create a debt request """
    if from_user == to_user:
        raise ValidationError("Users cannot be in debt with themselves")

    request, created = DebtRequest.objects.get_or_create(
        from_user=from_user,
        to_user=to_user,
        paying_user=paying_user,
        receiving_user=receiving_user,
        amount=amount,
        currency=currency,
        description=description,
        date_incurred=date_incurred,
        deadline=deadline,
        payed=payed,
        overdue=overdue)

    debt_request_created.send(sender=request)
    return request

在我看来,我有以下内容:

class DebtRequestCreate(generics.GenericAPIView):
    permission_classes = (IsAuthenticated,)

    def post(self, request, *args, **kwargs):
        other_user = User.objects.get(pk=request.data["friend_pk"])
        amount = request.data["amount"]
        currency = request.data["currency"]
        description = request.data["description"]
        date_incurred = request.data["date_incurred"]
        deadline = request.data["deadline"]
        is_payed = request.data["is_payed"]
        is_overdue = request.data["is_overdue"]

        is_in_debt = request.data["is_in_debt"]

        debt = None
        if is_in_debt: # is the request.user in debt
            debt = Debt.objects.add_debt(
                request.user, # From user
                other_user, # To user
                request.user, # Paying user                     
                other_user, # Receiving user
                amount, currency, description, date_incurred,
                deadline, is_payed, is_overdue)
        else:
            debt = Debt.objects.add_debt(
                request.user, # From user
                other_user, # To user
                other_user, # Paying user                     
                request.user, # Receiving user
                amount, currency, description, date_incurred,
                deadline, is_payed, is_overdue)

        return Response(status=201)

我想返回debt对象的json版本,而不是返回状态代码。我有以下函数用于将Debt对象列表转换为另一个视图中的json:

其他观点重要代码:

debt_requests_list = Debt.objects.requests(user=request.user)
debt_requests_list_json = json.loads(serializers.serialize('json', debt_requests_list))

debt_requests_json = [debt_requests_json_format(x, request.user.id) 
    for x in debt_requests_list_json]

return JsonResponse(debt_requests_json, safe=False)

功能:

def debt_requests_json_format(x, user_pk):
    fields = x["fields"]
    # if == True --> Debt request addressed to current user.
    if fields["to_user"] == user_pk:
        return {"pk": x["pk"],
        "created": fields["created"],
        "is_user_to_user": True,
        "current_user_pk": user_pk,
        "from_user": fields["from_user"],
        "from_user_first_name": User.objects.get(pk=fields["from_user"]).firstName,
        "from_user_last_name": User.objects.get(pk=fields["from_user"]).lastName,
        "paying_user": fields["paying_user"],
        "receiving_user": fields["receiving_user"],
        "amount": fields["amount"],
        "currency": fields["currency"],
        "payed": fields["payed"],
        "description": fields["description"],
        "date_incurred": fields["date_incurred"],
        "deadline": fields["deadline"],
        "overdue": fields["overdue"]}
    else: # if == False --> Debt request has been sent by current user.
        return {"pk": x["pk"],
        "created": fields["created"],
        "is_user_to_user": False,
        "current_user_pk": user_pk,
        "to_user": fields["to_user"],
        "to_user_first_name": User.objects.get(pk=fields["to_user"]).firstName,
        "to_user_last_name": User.objects.get(pk=fields["to_user"]).lastName,
        "paying_user": fields["paying_user"],
        "receiving_user": fields["receiving_user"],
        "amount": fields["amount"],
        "currency": fields["currency"],
        "payed": fields["payed"],
        "description": fields["description"],
        "date_incurred": fields["date_incurred"],
        "deadline": fields["deadline"],
        "overdue": fields["overdue"]}

我可以使用此函数将单个债务对象转换为json并使用JsonResponse将其返回给我的客户端吗?

0 个答案:

没有答案