'API view returning { "detail": "Not found." },
class User(models.Model):
user_id = models.CharField(max_length=255, unique=True)
mobile = models.CharField(max_length=12)
first_name = models.CharField(max_length=200, null=True)
last_name = models.CharField(max_length=200, null=True)
profile_image = models.URLField(null=True)
email = models.EmailField(null=True)
posts = models.ManyToManyField('uploads.Posts', related_name='post_user')
created_on = models.DateTimeField(default=timezone.localtime)
updated_on = models.DateTimeField(default=timezone.localtime)
is_deleted = models.BooleanField(default=False)
class Posts(models.Model):
url = models.URLField(null=True)
description = models.TextField()
created_on = models.DateTimeField(default=timezone.localtime)
updated_on = models.DateTimeField(default=timezone.localtime)
is_deleted = models.BooleanField(default=False)
These are my models, I have created a serializer for Posts and nested it under a UserPostSerializer.
class PostSerializer(serializers.ModelSerializer):
class Meta:
model = Posts
exclude = ('id', 'created_on', 'updated_on', 'is_deleted')
class UserPostsSerializer(serializers.ModelSerializer):
posts = PostSerializer(many=True)
class Meta:
model = User
fields = ('user_id', 'posts',)
However, when I create a view like this:
class UserPostsView(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserPostsSerializer
def list(self, request, *args, **kwargs):
queryset = self.get_queryset()
serializer = self.get_serializer(queryset, many=True)
response = Response(serializer.data)
return response
my API returns { "detail": "Not found." }
Ideally, the view should list all the users along with their posts. Something like:
{
"user_id": "abcd",
"posts": {
"url": "http:....com",
"description": "Lorem ipsum"
}
}
Solution 1:[1]
The issue was with the ordering of the URLs, I had called it this way:
urlpatterns = [
path('list', UserListView.as_view(), name='user list'),
path('<str:id>', UserDetailView.as_view(), name='user detail'),
path('posts', UserPostsView.as_view(), name='user posts')]
this way it was mapping my request to UserDetailView, since < str:id > is a catch-all and was called before 'posts', Django was trying to find an user with an user_id 'posts'. The URL for my UserPostsView should have preceded the URL for my UserDetailView, like:
urlpatterns = [
path('list', UserListView.as_view(), name='user list'),
path('posts', UserPostsView.as_view(), name='user posts'),
path('<str:id>', UserDetailView.as_view(), name='user detail')]
This fixes the error and I am able to see the data in the required format.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Yogeesh |
