Django Rest Framework:无法使用视图名称 "post-detail" 解析 URL 超链接关系

Django Rest Framework: Could not resolve URL for hyperlinked relationship using view name "post-detail"

我找到了很多类似问题的答案,但其中 none 对我有帮助。 我是后端和 Django 的新手,我已经花了几天时间试图找出我做错了什么,但没有成功。 我将不胜感激任何帮助! 所以,当我打电话给 http://127.0.0.1:8000/users/{user_name}/ 我得到:

ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "post-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.

如果我在任何其他字段上更改 HyperlinkedRelatedField 它工作正常...

urls.py

 app_name = 'api'
urlpatterns = [
        url(r'^posts/(?P<post_id>\d+)/$', PostDetails.as_view(),
            name='post-detail'),
        url(r'^users/(?P<username>[\w\-]+)/$', UserPosts.as_view()),
    ]

views.py

class PostDetails(APIView):
    """
        - GET a post

    """

    def get(self, request, post_id):

        post = Post.objects.get(id=post_id)
        post_serializer = PostSerializer(post)

        return Response(post_serializer.data)

class UserPosts(APIView):
    """
        GET all user posts
    """

    def get(self, request, username):
        user = User.objects.get(username=username)
        serializer = UserSerializer(user, context={'request': request})
        return Response(serializer.data)

serializer.py

  class UserSerializer(serializers.ModelSerializer):
    posts = serializers.HyperlinkedRelatedField(many=True,
                                                read_only=True,
                                                view_name='post-detail',
                                                lookup_field='id')
    #  Mandatory for UUID serialization
    user_id = serializers.UUIDField()

    class Meta:
        model = User
        exclude = ('id', 'password')
        read_only_fields = ('created', 'username', 'posts',)


class PostSerializer(serializers.ModelSerializer):

    author = UserSerializer()

    class Meta:
        model = Post
        fields = '__all__'

models.py

     class User(models.Model):
   username = models.CharField(max_length=30, unique=True)
   password = models.CharField(max_length=50)
   email = models.EmailField(unique=True)
   first_name = models.CharField(max_length=30)
   last_name = models.CharField(max_length=30)
   phone = models.CharField(max_length=20, blank=False, unique=True)
   user_id = models.UUIDField(editable=False,
                           unique=True,
                           null=False,
                           db_index=True,)
  created = models.DateTimeField()
  id = models.BigAutoField(primary_key=True)

  class Meta:
      ordering = ('created',)

  def __unicode__(self):
      return "Email: %s " % self.email


class Post(models.Model):
   created = models.DateTimeField()
   is_active = models.BooleanField(default=False)
   title = models.CharField(max_length=200, blank=False)
   body_text = models.CharField(max_length=1000, blank=False)
   address = models.CharField(max_length=100)
   author = models.ForeignKey(User, on_delete=models.PROTECT,
                           related_name='posts')
   price = models.DecimalField(max_digits=10, decimal_places=0)
   id = models.BigAutoField(primary_key=True)

  class Meta:
      ordering = ('created',)

  def __unicode__(self):
      return "Title : %s , Author:  %s  " % (self.title, self.author)

您的 lookup_field 与您的 url 不匹配 post_id

url(r'^posts/(?P<post_id>\d+)/$', PostDetails.as_view(),
        name='post-detail'),

来自文档:

  • lookup_field - 应该用于查找的目标上的字段。应对应于引用视图上的 URL 关键字参数。默认为 'pk'.
  • lookup_url_kwarg - URL conf 中定义的与查找字段对应的关键字参数的名称。默认使用与 lookup_field.
  • 相同的值

所以你应该没问题:

posts = serializers.HyperlinkedRelatedField(many=True,
                                            read_only=True,
                                            view_name='post-detail',
                                            lookup_url_kwarg='post_id')