代码之家  ›  专栏  ›  技术社区  ›  Lutaaya Huzaifah Idris

字段名“Field_name”对模型无效

  •  0
  • Lutaaya Huzaifah Idris  · 技术社区  · 4 年前

    我有以下博客文章的序列化程序:

    class TagSerializer(serializers.ModelSerializer):
        """Tag Serializer."""
        owner = serializers.ReadOnlyField(source='owner.username')
        posts = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    
        class Meta:
            model = Tag
            fields = ('id', 'name', 'owner', 'posts',)
    
    
    class PostSerializer(serializers.ModelSerializer):
        """Post Serializer"""
        owner = serializers.ReadOnlyField(source='owner.username')
        comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    
        class Meta:
            model = Post
            fields = ('id', 'title', 'body', 'owner', 'comments', 'tags', )
    

    以及以下型号:

    class Post(TimeStampedModel, models.Model):
        """Post model."""
        title = models.CharField(_('Title'), max_length=100, blank=False, null=False)
        body = models.TextField(_('Body'), blank=False)
        owner = models.ForeignKey(User, related_name='posts',
                                  on_delete=models.CASCADE)
    
        class Meta:
            ordering = ['created']
    
        def __str__(self):
            """
            Returns a string representation of the blog post.
            """
            return f'{self.title} {self.owner}'
    
    
    class Tag(models.Model):
        """Tags model."""
        name = models.CharField(max_length=100, blank=False, default='')
        owner = models.ForeignKey(User, related_name='tags_owner',
                                  on_delete=models.CASCADE)
        posts = models.ManyToManyField('Post', related_name='tags_posts',
                                       blank=True)
    
        class Meta:
            verbose_name_plural = 'tags'
    
        def __str__(self):
            """
            Returns a string representation of the category post.
            """
            return f'{self.name}'
    

    我想知道我为什么会收到这个错误:

    enter image description here

    我什么时候得到博客帖子列表

    最后是我的看法:

    class PostList(generics.ListCreateAPIView):
        """Blog post lists"""
        queryset = Post.objects.all()
        serializer_class = serializers.PostSerializer
        permission_classes = [permissions.IsAuthenticatedOrReadOnly]
    
        def perform_create(self, serializer):
            serializer.save(owner=self.request.user)
    
    1 回复  |  直到 4 年前
        1
  •  2
  •   Nick ODell    4 年前

    这是由两段代码引起的。

    首先,您的标记模型:

    class Tag(models.Model):
        [...]
        posts = models.ManyToManyField('Post', related_name='tags_posts',
                                       blank=True)
    

    其次,您的后期序列化程序:

    class PostSerializer(serializers.ModelSerializer):
        [...]
    
        class Meta:
            model = Post
            fields = (... 'tags', )
    

    您的帖子序列化程序需要一个名为“tags”的字段。在ManyToManyField中,您将相关的_名称设置为“tags_posts”。这两个字段不匹配,导致了问题。您必须将要序列化的字段更改为tags\u post,或者更改相关的\u名称,如下所示:

    class Tag(models.Model):
        [...]
        posts = models.ManyToManyField('Post', related_name='tags',
                                       blank=True)
    

    What is related_name used for?

    推荐文章