I have two Django models:
- Book -- which has some Wagtail StreamFields:
class Book(models.Model):
title = models.CharField(max_length=255)
cover_image = StreamField(...)
...
- Publisher -- which is pure Django:
class Publisher(models.Model):
name = models.CharField(max_length=255)
...
I wanted to have a PublisherChooser in my Wagtail admin. So I [created all that was required and then] added a field to my Book model:
class Book(models.Model):
title = models.CharField(max_length=255)
cover_image = StreamField(...)
...
publisher = models.CharField(max_length=10)
panels = [
FieldPanel("title"),
FieldPanel("cover_image"),
FieldPanel("publisher", widget=PublisherChooser),
]
Now I have a proper PublisherChooser whenever I want to create a Book in Wagtail Admin.
Problem
Now I want to serialize my Book model. So I have tried:
class PublisherSerializer(serializers.ModelSerializer):
class Meta:
model = Publisher
fields = [
"name",
...
]
name = serializers.CharField()
...
and
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = [
"title",
"cover_image",
...,
"publisher",
publisher = serializer.PrimaryKeyRelatedField(queryset=Publisher.objects.all())
def update(self, instance, validated_data):
publisher = validated_data.pop("publisher")
instance.publisher_id = publisher.id
return instance
def to_representation(self, instance):
data = super().to_representation(instance)
publisher_serializer = PublisherSerializer(
Publisher, context={"pk": instance.publisher}
)
data["publisher"] = publisher_serializer.data
return data
I get publisher in the response but the publisher data doesn't seem to look right:
"publisher": {
"name": "<django.db.models.query_utils.DeferredAttribute object at 0x7f9ffa146310>",
}