如何从基于django rest frameworks类的创建视图向我的用户配置文件中的M2M字段添加对象?

时间:2015-12-15 20:58:40

标签: python django django-rest-framework

我正在尝试让用户在DRF通用创建视图的用户配置文件中将媒体添加到其媒体字段。有没人试过这个?这是我的观点和模型:

class MediaCreate(generics.CreateAPIView):
"""
    To create a media object, send a post request to:
        /profiles/media/create/
    In the format:
        Audio: "audio file upload"
        Title: "char field"
"""
queryset = Media.objects.all()
serializer_class = MediaSerializer



class Musician(ProfileModel):
    summary = models.TextField(blank=True)
    company = models.CharField(max_length=60, blank=True)
    media = models.ManyToManyField('Media', blank=True)
    timestamp = models.DateTimeField(auto_now_add=True, blank=True)


def __str__(self):
    return '{}'.format(self.user.username)

2 个答案:

答案 0 :(得分:1)

所以我决定用函数api视图来做这个,所以我可以使用请求将模型添加到配置文件,而不需要任何get请求 我知道检查方法==帖子是多余的,但它不会伤害任何东西:

   @api_view(['POST'])
   def MediaCreate(request):
       context = {}
       logged_on = False
       if request.user.is_authenticated():
          logged_on = True
          visitor = request.user.musician
          serializer = MediaSerializer(data=request.data)
          if request.method == "POST":
              if serializer.is_valid():
                 serializer.save()
                 try:
                    x = serializer.instance
                    visitor.media.add(x)
                    context['upload'] = True
                 except:
                    error = "Media Not Added to Profile"
                    context['logged_on', 
                             'error', 
                              'upload'] = logged_on, error, False
                    return JsonResponse(
                                      data=context,
                                  status=status.HTTP_400_BAD_REQUEST)
      context['logged_on'] = logged_on
      return JsonResponse(data=context, status=status.HTTP_200_OK)

答案 1 :(得分:0)

您需要在 serializers.py 中定义两个类:

class MediaSerializer(serializers.ModelSerializer):

    class Meta:
        model = Media

class MusicianSerializer(serializers.ModelSerializer):
    media = MediaSerializer(many=True, read_only=true)

    class Meta:
        model = Musician

为了更新特定音乐家的媒体字段,您只发送media_id而不是整个对象,如下例所示:

data = {
    "summary": "text summary here"
    "company": "Company A"
    "media_id": 3 
}

views.py 中,您应该定义以下视图并覆盖get_object以满足您的需求:

class MusicianUpdatingApiView(generics.UpdateAPIView):
    """
    To add a media to a user, send a post request to:
    /profiles/:id/media
    """
    serializer_class = MusicianSerializer

    def get_object(self):
        summary = self.request.data.get("summary")
        company = self.request.data.get("company")
        media_id = self.request.data.get("media_id")
        musician_id = self.kwargs['id'] # cause it send in the url
        data = {
             "summary": summary
             "company": company
             "media_id": media_id 
        }
        updated_musician, created = Musician.objects.update_or_create(
                id=musician_id,
                defaults=data
            )
        return updated_musician
urls.py

url(r'^profiles/(?P<id>\d+)/media$', MusicianUpdatingApiView.as_view()),