如何从视图中访问django模型属性?

时间:2017-08-07 07:51:25

标签: python django django-models django-views

我有一个django模型:

class DebtRequest(models.Model):
    from_user = models.ForeignKey(User, related_name='debt_requests_from_user')
    to_user = models.ForeignKey(User, related_name='debt_requests_to_user')

    paying_user = models.ForeignKey(User, related_name='debt_requests_paying_user')
    receiving_user = models.ForeignKey(User, related_name='debt_requests_receiving_user')

    amount = models.FloatField()
    currency = models.CharField(max_length=10, default="USD")
    description = models.CharField(max_length=100, blank=True)
    date_incurred = models.DateTimeField(default=timezone.now)
    deadline = models.DateTimeField()
    payed = models.BooleanField(default=False)
    overdue = models.BooleanField(default=False)
    created = models.DateTimeField(default=timezone.now)

    @property
    def time_since_created(self):
        return (timezone.now() - self.created).total_seconds()

以下是我的观点:

class ListDebtRequests(generics.ListAPIView):
    permission_classes = (IsAuthenticated,)

    def get(self, request, format=None):
        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)

这是函数debt_requests_json_format

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"],
        "time_since_created": fields["time_since_created"],
        "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"]}

我需要理想地从这里访问模型属性或将其传递给函数。

time_since_created属性返回自模型实例创建以来的秒数,但我不知道如何从我的视图中访问它。

如何从我的视图中访问此内容?

1 个答案:

答案 0 :(得分:1)

我尝试使用额外字段为您的模型定义示例序列化程序。这是一个非常简单的例子。

class DebtRequestSerializer(serializers.ModelSerializer):
    is_user_to_user = serializers.SerializerMethodField()
    current_user_pk = serializers.SerializerMethodField()
    time_since_created = serializers.IntegerField(source='time_since_created')
    to_user_first_name = serializers.CharField(source='to_user.firstName')

    class Meta:
        model = DebtRequest

    def get_is_user_to_user(self, obj):
        return obj.to_user == self.context.get('request').user.id

    def get_current_user_pk(self, obj):
        return self.context.get('request').user.id

更多详情:rest-framework fields