Django rest框架自动填充user.id

时间:2014-03-26 17:28:07

标签: python django rest auto-populate

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

models.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

serializers.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' )

1 个答案:

答案 0 :(得分:9)

Django Rest Framework提供了一个pre_save()方法(在通用视图和mixins中),您可以覆盖它。

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

然后在你的视图类中出现类似的内容:

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