#model.py file
class FileModel(models.Model):
file = models.FileField(verbose_name=_('File'))
title = models.CharField(max_length=255, verbose_name=_('Title'))
start_time_to_creating = models.DateTimeField(verbose_name=_('Start Time To Creating'))
created_time = models.DateTimeField(auto_now_add=True, verbose_name=_('Created Time'))
time_to_deleting = models.DateTimeField(null=True, blank=True, verbose_name=_('when_it_will_be_deleted'))
page_count = models.PositiveIntegerField(null=True, blank=True, verbose_name=_('Page Count'))
row_count = models.PositiveIntegerField(null=True, blank=True, verbose_name=_('Row Count'))
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, verbose_name=_('User'))
#serializers.py file
class FileSerializer(serializers.ModelSerializer):
class Meta:
model = FileModel
fields = ['id', 'file', 'title', 'start_time_to_creating', 'created_time', 'time_to_deleting', 'page_count',
'row_count']
#views.py file
class FileListByUserView(generics.ListAPIView):
queryset = FileModel.objects.all()
serializer_class = FileSerializer
filter_backends = (DjangoFilterBackend, OrderingFilter)
filterset_class = FileFilter
ordering_fields = ['created_time', 'title']
ordering = ['-created_time']
def get_queryset(self):
user_id = self.kwargs.get('user_id')
return super().get_queryset().filter(user=user_id)
#urls.py file
urlpatterns = [
url(r'^list/(?P<user_id>[0-9]+)/?$', FileListByUserView.as_view(), name='file-list-by-user')
]
I serialize my FileModel model with FileSerializer and get it as a response. I want to test this. but I could not give the request object to the FileSerializer serializer that I used in unit test. So the file url does not match the data in the response because I cannot make the absolute url and it falls into error.
from rest_framework.test import APIClient
class TestBase(TransactionTestCase):
reset_sequences = True
def setUp(self):
super().setUp()
self.client = APIClient()
def test_list_by_user(self):
response = self.client.get(reverse('file-list-by-user', kwargs={'user_id': 1}))
self.assertEqual(response.status_code, 200)
file_models = FileModel.objects.all()
file_serializer_data = FileSerializer(instance=file_models, many=True, context={'request': }).data
content = str(response.content, encoding="utf8")
content_json = json.loads(content)
self.assertEqual(file_serializer_data, content_json)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…