python - 如何在 Django Rest Framework 中获取模型方法的值?

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

所以基本上我有一个 Django 模型,它有一个 ManyToManyField friend 和两个在它上面运行的方法。这是我的文件:

模型.py:

from django.db import models
from django.contrib.auth.models import User


class Profile(models.Model):
    first_name = models.CharField(max_length=50, blank=True)
    last_name = models.CharField(max_length=50, blank=True)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    friends = models.ManyToManyField(User, blank=True, related_name='friends')

    def friends_list(self):
        return self.friends.all()

    def number_of_friends(self):
        return self.friends.all().count()

序列化器.py:

from rest_framework import serializers
from .models import Profile


class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = '__all__'

Views.py:

from rest_framework import viewsets, permissions
from .models import Profile
from .serializers import ProfileSerializer


class ProfileViewSet(viewsets.ModelViewSet):
    queryset = Profile.objects.all()
    permission_classes = [
        permissions.AllowAny
    ]
    serializer_class = ProfileSerializer

问题是在 Api 中,方法的返回值不存在。例如,friends_list 方法应该返回您拥有的 friend 列表,即使这在传统的 django 项目中确实有效,但 Django Rest Framework 并未显示此方法的任何值(value)。我该如何解决这个问题并让这两种方法的返回值显示在 API 中?

最佳答案

由于模型序列化程序只为序列化程序字段选择模型字段,因此您不会自动复制任何方法。

通过引用模型方法显式添加两个字段,您仍然可以通过 API 发送此只读数据

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = [
            # need to explicitly define all fields I believe
            'friends_list',
            'number_of_friends',
        ]

既然声明了两个字段(匹配方法名,DRF 应该为每个创建SerializerMethodFieldReadOnly 字段(不确定是哪一个,但它们是相似的)他们中的。 它之所以有效,是因为它将这些字段的源设置为相同的名称,并且如果在模型上找到某些属性(在本例中为方法)。

如果不行,你可以

class ProfileSerializer(serializers.ModelSerializer):
    friends_list = serializers.SerializerMethodField()
    number_of_friends = serializers.SerializerMethodField()

    class Meta:
        model = Profile
        fields = [
            # need to explicitly define all fields I believe
            'friends_list',
            'number_of_friends',
        ]

    def get_friends_list(self, instance):
        return instance.friends_list()

    def get_number_of_friends(self, instance):
        return instance.number_of_friends()

关于python - 如何在 Django Rest Framework 中获取模型方法的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64852493/

相关文章:

django - 文件未找到错误: [Errno 2] No such file or directory: '/app/static'

django - DRF - 如何让 WritableField 不将整个数据库加载到内存中?

python - 在 save() 重写中读取外键引用引发 RelatedObjectDoesNotExist

python - 如何为 python 2.7.9 安装 numpy

python - Mac OS X + Python + Django + MySQL

python - `pytest` : Downloading a test file once, 并将其用于多个测试

python - 无法让 VS Code 将参数从 launch.json 传递给 Python

python - Django 1.9 日期时间过滤器

python - 更新记录时发生 Django IntegrityError

Django 自定义验证器不工作