gpt4 book ai didi

python - Django rest 框架使用 user.id 自动填充字段

转载 作者:太空狗 更新时间:2023-10-30 02:04:15 31 4
gpt4 key购买 nike

我找不到自动填充模型字段所有者的方法。我使用的是 DRF。如果我使用 ForeignKey,用户可以从下拉框中选择所有者,但这没有意义。PLZ帮助我无法让它工作。views.py 不包括在内,因为我认为这与它无关。

模型.py

class Note(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
cr_date = models.DateTimeField(auto_now_add=True)
owner = models.CharField(max_length=100)
# also tried:
# owner = models.ForeignKey(User, related_name='entries')

class Meta:
ordering = ('-cr_date',)

def __unicode__(self):
return self.title

序列化器.py

class UserSerializer(serializers.ModelSerializer):

class Meta:
model = User
fields = ('id', "username", 'first_name', 'last_name', )

class NoteSerializer(serializers.ModelSerializer):
owner = request.user.id <--- wrong , but is what a need.
# also tried :
# owner = UserSerializer(required=True)

class Meta:
model = Note
fields = ('title', 'body' )

最佳答案

Django Rest Framework 提供了一个您可以覆盖的 pre_save() 方法(在通用 View 和混合中)。

class NoteSerializer(serializers.ModelSerializer):
owner = serializers.Field(source='owner.username') # Make sure owner is associated with the User model in your models.py

然后在你的 View 类中这样的东西:

def pre_save(self, obj):
obj.owner = self.request.user

引用资料

http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions#associating-snippets-with-users

https://github.com/tomchristie/django-rest-framework/issues/409#issuecomment-10428031

关于python - Django rest 框架使用 user.id 自动填充字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22668674/

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