Skip to content
Advertisement

Django/Wagtail Snippet Serializer in API

I have added wagtail CMS’s blog author in my ‘models.py’ also exposed it in API, but it’s showing like this in API

"blog_authors": [
        {
            "id": 1,
            "meta": {
                "type": "blog.BlogAuthorsOrderable"
            }
        }
    ],

Here’s the models.py code

class BlogAuthorsOrderable(Orderable):
    """This allows us to select one or more blog authors from Snippets."""

    page = ParentalKey("blog.AddStory", related_name="blog_authors")
    author = models.ForeignKey(
        "blog.BlogAuthor",
        on_delete=models.CASCADE,
    )

    panels = [
        # Use a SnippetChooserPanel because blog.BlogAuthor is registered as a snippet
        SnippetChooserPanel("author"),
    ]


@register_snippet
class BlogAuthor(models.Model):
    """Blog author for snippets."""

    name = models.CharField(max_length=100)
    website = models.URLField(blank=True, null=True)
    image = models.ForeignKey(
        "wagtailimages.Image",
        on_delete=models.SET_NULL,
        null=True,
        blank=False,
        related_name="+",
    )

    panels = [
        MultiFieldPanel(
            [
                FieldPanel("name"),
                # Use an ImageChooserPanel because wagtailimages.Image (image property)
                # is a ForeignKey to an Image
                ImageChooserPanel("image"),
            ],
            heading="Name and Image",
        ),
        MultiFieldPanel(
            [
                FieldPanel("website"),
            ],
            heading="Links"
        )
    ]

    def _str_(self):
        """String repr of this class."""
        return self.name

    class Meta:  # noqa
        verbose_name = "Blog Author"
        verbose_name_plural = "Blog Authors"

How do I serialize like this show author name, website, image and id?

I tried to Serialize the BlogAuthor

class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = BlogAuthor
        fields = (
            "id",
            "name",
            "website",
            "image",
        )

And here is the API field

APIField("blog_authors", serializer=AuthorSerializer(many=True)),

When I runserver I got this error

AttributeError at /api/v2/pages/4/
Got AttributeError when attempting to get a value for field `name` on serializer `AuthorSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `BlogAuthorsOrderable` instance.
Original exception text was: 'BlogAuthorsOrderable' object has no attribute 'name'.
Request Method: GET
Request URL:    http://127.0.0.1:8000/api/v2/pages/4/?fields=*
Django Version: 4.0.6
Exception Type: AttributeError
Exception Value:    
Got AttributeError when attempting to get a value for field `name` on serializer `AuthorSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `BlogAuthorsOrderable` instance.
Original exception text was: 'BlogAuthorsOrderable' object has no attribute 'name'.

How I can perfectly serialize my blog author?

Advertisement

Answer

I think the problem is there is an intermediate model between your Blog and BlogAuthor – the BlogAuthorsOrderable that has the sort_order field. I don’t know how to get exactly what you are asking for but try changing your AuthorSerializer as follows. Hopefully that will give you enough information to figure out your next steps.

class AuthorSerializer(serializers.ModelSerializer):
class Meta:
    model = BlogAuthorsOrderable
    fields = '__all__'
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement