[Answered ]-DRF one-to-one relation serializer with a pre-populated model

1👍

models.py:

class Book(models.Model):
    day = models.CharField(max_length=128)
    book = models.CharField(max_length=128)
    chapter = models.CharField(max_length=256)
    paragraph = models.CharField(max_length=256)
    text = models.TextField()
    link = models.CharField(max_length=256)

    def __str__(self):
        return f'{self.book}_{self.chapter}.{self.paragraph} '

    class Meta:
        ordering = ['-id']

class Note(models.Model):
    owner = models.ForeignKey(to = User, related_name='author', on_delete=models.CASCADE)
    book = models.ForeignKey(Book, related_name='note', on_delete=models.CASCADE)
    created = models.DateTimeField(auto_now_add=True)
    text = models.TextField(default=None)
    
    def __str__(self):
        return '%s(%s)' %(self.owner,self.book)

serializers.py:

class NoteSerializer(serializers.ModelSerializer):
    class Meta:
        model = Note
        fields = ['id', 'owner', 'book', 'text', 'created']
        
class BookSerializer(serializers.ModelSerializer):
    note = serializers.StringRelatedField(many=True, read_only=True)
    # note = NoteSerializer(many=True, read_only=True)
    class Meta:
        model = Book
        fields = ['day','book','chapter','paragraph','text','link','note']

Output:

{
    "day": "2",
    "book": "some book",
    "chapter": "1",
    "paragraph": "example",
    "text": "some textttttttttttttttttttttttttttttttttttttttttttttttt",
    "link": "http://127.0.0.1:8000/admin/api/book/add/",
    "note": [
        "admin(some book_1.example )"
    ]
}

It’s return all field:

class NoteSerializer(serializers.ModelSerializer):
    class Meta:
        model = Note
        fields = ['id', 'owner', 'book', 'text', 'created']
        
class BookSerializer(serializers.ModelSerializer):
    # note = serializers.StringRelatedField(many=True, read_only=True)
    note = NoteSerializer(many=True, read_only=True)
    class Meta:
        model = Book
        fields = ['day','book','chapter','paragraph','text','link','note']

Output:

{
    "day": "2",
    "book": "some book",
    "chapter": "1",
    "paragraph": "example",
    "text": "some textttttttttttttttttttttttttttttttttttttttttttttttt",
    "link": "http://127.0.0.1:8000/admin/api/book/add/",
    "note": [
        {
            "id": 2,
            "owner": 1,
            "book": 1,
            "text": "saaaaaaaaaaaaaaaaaaa",
            "created": "2021-02-24T14:34:13.279750Z"
        }
    ]
}

0👍

What you’re actually trying to achieve is for the NoteSerializer to include fields from the Foreign-key related book model. Overriding the to_representation method of the serializer is clunky and not the way to go. See here a better approach.

Leave a comment