Convert "ManyToManyField" in the Django rest platform

I am using the Django-rest-framework to create an API. I have a model. ChairI create a viewet for. It has ManyToManyFieldfor the model Tag, so each chair has several tags.

Tag- this is a Django model, but when interacting with the API, I do not want to see a JSON dict for each tag; I just want to use the tag name.

eg. when viewing Chairin the API, I want to see that it has this:

{
    'tags': ['meow', 'frrr', 'nutella'],
     ... Any other chair attributes
}

And in a similar way, when I create Chair, I want to be able to pass a list of tag names, and then make get_or_createthat name for each of them . (So ​​I either use an existing tag with this name, or create a new one.)

How to put all this logic in your serializer / view?

+4
source share
1 answer

define your tag field in the serializer as follows:

tags = serializers.SlugRelatedField(slug_field='name', many=True)

Now for get_or_create behavior, my suggestion would be to use the django form. You will have to override the post method (or create a method if you use the viewet), and write a regular django method to create material using forms.

Take a look at request.DATA is a regular python dictionary, use it as data for your chair form.

The form will accept this data, and then you can check the data as usual, as in the django form.

Then create an instance of the chair using:

chair = form.save(commit=False)
chair.save()

Once you have an instance of the chair with you, you can add as many tags using:

chair.tags.add(tag1, tag2, tag3...)

python, .DATA dict get_or_create. - :

tags = []
tags_name_list = request.DATA['tags']
for tag_name in tags_name_list:
    tag = Tag.objects.get_or_create(name=tag_name)
    tags.append(tag)

. :

chair.tags.add(*tags)
+2

Source: https://habr.com/ru/post/1527721/


All Articles