Lutaaya Huzaifah Idris
Lutaaya Huzaifah Idris

Reputation: 4020

Field name 'field_name' is not valid for model Model

I am having the following serializers of a blog post :

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', )

and the following models :

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}'

I am wondering why am recieveing this error :

enter image description here

When am getting the list of blog posts

Finally here is my views :

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)

Upvotes: 0

Views: 1703

Answers (1)

Nick ODell
Nick ODell

Reputation: 25454

This is caused by two pieces of code.

First, your tag model:

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

Second, your post serializer:

class PostSerializer(serializers.ModelSerializer):
    [...]

    class Meta:
        model = Post
        fields = (... 'tags', )

Your post serializer expects a field named 'tags.' In the ManyToManyField, you set the related_name to 'tags_posts.' These two do not match and it is causing the problem. You must either change the field you're serializing to tags_post, or change the related_name like this:

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

See also: What is related_name used for?

Upvotes: 2

Related Questions