我发布的是使用API在模型Movie中创建新条目。使用标题,我希望能够POST,以便OWNER是发布它的用户。用户令牌通过标头发送。
models.py
@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
if created:
Token.objects.create(user=instance)
class Movie(models.Model):
title = models.CharField("Title", max_length=10000, blank=True)
tag = models.ManyToManyField('Tag', blank=True)
created = models.DateTimeField("Created", auto_now_add=True)
owner = models.ForeignKey('auth.User', blank=True, null=True)
Views.py
class OwnerFilterBackend(filters.BaseFilterBackend):
def filter_queryset(self, request, queryset, view):
return queryset.filter(owner=request.user)
class AllViewSet(viewsets.ModelViewSet):
filter_backends = (OwnerFilterBackend,)
queryset = Movie.objects.order_by('-created',).exclude(deleted=True).exclude(typetask=2)
serializer_class = AllSerializer
Serializers.py
class AllSerializer(serializers.ModelSerializer):
tag = TagSerializer(many=True, read_only=True)
class Meta:
model = Movie
fields = ('title', 'mail', 'pk', 'tag', 'info', 'created', 'deleted', 'status', 'typetask')
def create(self, validated_data):
tags_data = validated_data.pop('tag')
movie = Movie.objects.create(**validated_data)
for tag_data in tags_data:
tag_qs = Tag.objects.filter(name__iexact=tag_data['name'])
if tag_qs.exists():
tag = tag_qs.first()
else:
tag = Tag.objects.create(**tag_data)
task.tag.add(tag)
return movie
答案 0 :(得分:1)
您可以使用context['request']
表单设置用户,默认情况下会在GenericAPIView
s中提供。 http://www.django-rest-framework.org/api-guide/serializers/#including-extra-context
def create(self, validated_data):
tags_data = validated_data.pop('tag')
owner = self.context['request'].user
movie = Movie.objects.create(owner=owner, **validated_data)
for tag_data in tags_data:
tag_qs = Tag.objects.filter(name__iexact=tag_data['name'])
if tag_qs.exists():
tag = tag_qs.first()
else:
tag = Tag.objects.create(**tag_data)
task.tag.add(tag)
return movie