gpt4 book ai didi

python - Django 休息 : create CRUD operations for OneToOne Field

转载 作者:太空狗 更新时间:2023-10-30 02:43:33 25 4
gpt4 key购买 nike

我正在尝试为 OneToOne 字段创建基本的 CRUD 操作。用户在登录时不需要设置配置文件。如何在需要时创建/更新/删除配置文件(假设用户已经在数据库中)?

我的模型是来自 Django REST 的默认用户模型,并且:

class UserProfile(models.Model):
user = models.OneToOneField(User)
location = models.CharField(max_length=50,blank=True)
title = models.CharField(max_length=80,blank=True)
#picture = models.ImageField(upload_to='user_imgs', blank=True)
website = models.URLField(blank=True)

我的 View 集是:

class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
filter_fields = ['id', 'username', 'email', 'first_name', 'last_name']

class UserProfileViewSet(viewsets.ModelViewSet):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
filter_fields = ['user_id', 'location', 'title', 'website']

并序列化:

class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
email = serializers.EmailField()
fields = ('id','username', 'email', 'first_name', 'last_name')


class UserProfileSerializer(serializers.HyperlinkedModelSerializer):
user_id = serializers.CharField(source='user.id')

class Meta:
model = UserProfile
fields = ('user_id', 'location','title','website')

最佳答案

我相信您希望将配置文件创建限制为当前登录的用户。您可以过滤当前用户的个人资料查询集,这样只有该用户的个人资料才能被登录用户访问。

class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
filter_fields = ['id', 'username', 'email', 'first_name', 'last_name']


class UserProfileViewSet(viewsets.ModelViewSet):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
filter_fields = ['user_id', 'location', 'title', 'website']

def get_queryset(self):
return super(UserProfileViewSet, self).get_queryset().filter(
user=self.request.user)

def perform_create(self, serializer):
serializer.save(user=user)

您将 user 字段设为只读,并保存在上述方法 perform_create 中,并始终分配给当前用户。

class UserProfileSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = UserProfile
fields = ('user', 'location','title','website')
read_only_fields = ('user',)

关于python - Django 休息 : create CRUD operations for OneToOne Field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33049822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com