User ForiegnKey现在在Django Rest Framework视图集中显示为字段

时间:2019-05-17 00:01:19

标签: python django django-rest-framework

我正在使用django rest框架为Web应用程序构建后端。我有一个配置文件模型,该模型具有引用Django用户的用户forieingkey。一切都在正确加载,除了一个问题,即django rest框架后端url中未显示“用户”字段,这样我可以将用户分配给我要创建的配置文件对象。有人知道为什么会这样吗...

enter image description here

models.py:

class Profile(models.Model):
    user = models.ForeignKey(
        User, on_delete=models.CASCADE
    )
    synapse = models.CharField(max_length=25, null=True)
    bio = models.TextField(null=True)
    profile_pic = models.ImageField(
        upload_to='./profile_pics/',
        max_length=150
    )
    facebook = models.URLField(max_length=150)
    twitter = models.URLField(max_length=150)
    updated = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.user.username + ' profile'

视图集:

from users.models import Profile
from users.api.serializers.ProfileSerializer import ProfileSerializer
from rest_framework import viewsets

class ProfileViewSet(viewsets.ModelViewSet):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    lookup_field = 'user__username'

url:

from users.api.views.ProfileView import ProfileViewSet
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r'', ProfileViewSet, base_name='profile')
urlpatterns = router.urls

序列化器:

from rest_framework import serializers

from users.models import Profile

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = (
            'id',
            'user',
            'synapse',
            'bio',
            'profile_pic',
            'facebook',
            'twitter'
        )
        depth=2

1 个答案:

答案 0 :(得分:0)

当您将深度设置为大于0 时,会发生这种情况,外键字段不可编辑(如果您发送的POST的字段包含一些值,DRF视图集将忽略它,并且如果该字段是必需的,它将引发异常。

一种解决方案是重写序列化器的to_representation()方法并设置深度并将其恢复为零:

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = (
            'id',
            'user',
            'synapse',
            'bio',
            'profile_pic',
            'facebook',
            'twitter'
        )

    def to_representation(self, instance):
        self.Meta.depth = 2
        representation = super().to_representation(instance)
        self.Meta.depth = 0

        return representation