Вопрос

I cant find a way to auto-populate the field owner of my model.I am using the DRF .If i use ForeignKey the user can choose the owner from a drop down box , but there is no point in that.PLZ HELP i cant make it work.The views.py is not include cause i think there is nothing to do with it.

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' )
Это было полезно?

Решение

Django Rest Framework provides a pre_save() method (in generic views & mixins) which you can override.

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

Then something like this in your view class:

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

REFERENCES

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top