[英]How can I add an object to a M2M field on my users profile from django rest frameworks class based create view?
I am trying to have a logged in user add Media to their media field in the users profile in a DRF generic create view. 我正在尝试让登录用户将媒体添加到DRF通用创建视图的用户配置文件中的媒体字段中。 Has anyone tried this? 有人尝试过吗? Here's my view and model: 这是我的观点和模型:
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)
So I decided to do this with a function api view instead so I can add the model to the profile using the request and not requiring any get request I know the check if method == Post is redundant but it doesn't harm anything: 因此,我决定改为使用函数api视图来执行此操作,以便我可以使用请求将模型添加到配置文件中,而不需要任何get请求,因为我知道方法== Post的检查是否多余,但它不会对任何内容造成损害:
@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)
all you need to do define in your serializers.py the two classes: 您需要在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
In order to update the media field for specific musician you send only the media_id and not the whole object as show the following example: 为了更新特定音乐家的媒体字段,您只发送media_id而不发送整个对象,如以下示例所示:
data = {
"summary": "text summary here"
"company": "Company A"
"media_id": 3
}
in your views.py you should define the following view and override get_object to fit your needs: 在您的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
in urls.py 在urls.py中
url(r'^profiles/(?P<id>\d+)/media$', MusicianUpdatingApiView.as_view()),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.