简体   繁体   English

如何在 Django Rest 框架中获取 model 方法的值?

[英]How to get value of model method in Django Rest Framework?

So basically I have a django model that has a ManyToManyField of friends and two methods that run on it.所以基本上我有一个 django model,它有一个 ManyToManyField 朋友和两个在其上运行的方法。 Here are my files:这是我的文件:

Models.py:模型.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()

Serialzers.py:序列化程序.py:

from rest_framework import serializers
from .models import Profile


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

Views.py:视图.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

The issue is that in the Api, the return values of the method aren't there.问题是在 Api 中,该方法的返回值不存在。 The friends_list method for example is supposed to return a list of friends you have and even though this does work in a traditional django project, the Django Rest Framework is not showing any value for this method.例如,friends_list 方法应该返回您拥有的朋友列表,即使这在传统的 django 项目中有效,Django Rest 框架也没有显示此方法的任何值。 How can I fix this and get the return values for both methods to show up in the api?我该如何解决这个问题并让这两种方法的返回值都显示在 api 中?

Since the model serializer picks up only model fields for the serializer fields, you won't automatically get any methods copied over.由于模型序列化程序仅选取序列化程序字段的模型字段,因此您不会自动复制任何方法。

You can still send this read only data over the API by explicitly adding the two fields with reference to the model methods您仍然可以通过参考模型方法显式添加两个字段来通过 API 发送此只读数据

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

Now that the two fields (matching the method name are declared, DRF should create SerializerMethodField or ReadOnly field (not sure which one, but they are similar) for each of them. It works coz it sets the source for those fields to be the same name, and if finds some attribute (in this case the methods) on the model.现在声明了两个字段(与方法名称匹配,DRF 应该为每个字段创建SerializerMethodFieldReadOnly字段(不确定哪个,但它们相似)。它可以工作,因为它将这些字段的源设置为相同名称,如果在模型上找到一些属性(在这种情况下是方法)。

If that doesn't work, you can如果这不起作用,你可以

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()

when you use __all__ it call fields only you have to call fields with methods using list like that当你使用__all__它只调用字段时,你必须使用像这样的列表的方法调用字段

`fileds = ["first_name","last_name","user",
           "friends","friends_list","number_of_friends"
           ]`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM