s_spirit
s_spirit

Reputation: 115

Serialize many-to-many relation with intermediate model in Django Rest

I tried to check another topics, but didn't found a solution...

I have a many-to-many model, that have intermediate model with another field additional_field inside.

class BoardField(models.Model):
    title = models.CharField(max_length=500, default='')

class Article(models.Model):
    title = models.CharField(max_length=500, default='')
    fields = models.ManyToManyField(BoardField, through='ArticleField', through_fields=('article', 'board_field'))

class ArticleField(models.Model):
    article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='task')
    board_field = models.ForeignKey(BoardField, on_delete=models.CASCADE)

    additional_field = models.CharField(max_length=200, blank=True, null=True)

I want serialize Article with structure:

[
    "title":"Title",
    "fields":[
        {
            "board_field": {
                "title":"Title"
            },
            "additional_field":"Additional info"
        }
    ]
]

So, I wrote serializer:

class BoardFieldSrl(serializers.ModelSerializer):

    class Meta:
        model = BoardField
        fields = (
            'title',
        )

class ArticleFieldSrl(serializers.ModelSerializer):

    board_field = BoardFieldSrl()

    class Meta:
        model = ArticleField
        fields = (
            'board_field',
            'additional_field',
        )

class ArticleListSrl(serializers.ModelSerializer):

    fields = ArticleFieldSrl(many=True)

    class Meta:
        model = Article
        fields = (
            'title',
            'fields',
        )

But I always got an error:

Got AttributeError when attempting to get a value for field `board_field` on serializer `ArticleFieldSrl`.
The serializer field might be named incorrectly and not match any attribute or key on the `BoardField` instance.
Original exception text was: 'BoardField' object has no attribute 'board_field'.

I made another several examples, but they doesn't gave my result, that I need... My maximum - I got BoardField with levels, but without intermediate model...

Can you help me with serializer, that return structure, that I mentioned above? It must include intermediate model ArticleField and nested BoardField.

Upvotes: 2

Views: 1313

Answers (1)

Mahmoud Adel
Mahmoud Adel

Reputation: 1330

Try fields = ArticleFieldSrl(source='articlefield_set', many=True)

You didn't specified a related_name at M2M field so the default naming is applied which is 'Intermediate model name'_set and if you want to use the fields on M2M relation you have to tell the serializer where to look for.

EDIT: Camel removed from articlefield_set, model name is always converted to lower case

Upvotes: 2

Related Questions