I use Django rest-framework which fetch the items from tables and return serialized json, when calling like this below
localhost/api/mixs?id=12
Source code.
class MixViewSet(viewsets.ModelViewSet):
serializer_class = MixSerializer
filter_backends = [django_filters.rest_framework.DjangoFilterBackend]
filter_fields = ["id","user"]
filterset_fields = ['id']
search_fields = ['id']
def list(self,request,*args,**kwargs):
queryset = self.filter_queryset(self.get_queryset())
serializer = self.get_serializer(queryset, many=True)
custom_data = {
'items': serializer.data
}
custom_data.update({
'meta':{"api":"Mix"}
})
return Response(custom_data)
def get_queryset(self):
queryset = Mix.objects.all()
ids = self.request.query_params.get('ids')
if ids is not None:
id_arr = ids.split(',')
if len(id_arr) > 0:
queryset = queryset.filter(id__in=id_arr)
u_key = self.request.query_params.get('u_key')
if u_key is not None:
queryset = queryset.filter(u_key=u_key)
return queryset
Now, I want to use this function from another method.
For example
def createMix(request):
#do something and make Mix
m = Mix(detail={},user=1)
m.save()
print(m.id) ### for example 13
#Now I want to do the equivalent thing
#to `localhost/api/mixs?id=13`
# returning the data id=13
obj = Mix.objects.get(id=m.id)
response = MixSerializer(obj)
print(response)
return Response(response)
#AssertionError: You passed a Serializer instance as data, but probably meant to pass serialized `.data` or `.error`. representation
When calling this url
localhost/myapp/createsong
The program do something and insert data in Mix table.
then do the equivalent thing to localhost/api/mixs?id=13
Is it possible?
Or my idea is correct?
CodePudding user response:
You can probaly do something like this. There is nothing restricts you from using test client as part of code.
from django.test.client import Client
c = Client()
article = c.post('/api/mixes', {
'id' : 13,
})