@Soulafein

В теле POST запроса передаю id, как в respons'e получить всю информацию по нему?

В теле POST запроса передаю список id, уже существующих объектов. Как в ответе получить полные данные этих объектов?
class RecipePostSerializer(serializers.ModelSerializer):
    author = CurrentUserProfileSerializer(read_only=True)
    tags = serializers.PrimaryKeyRelatedField(queryset=Tags.objects.all(), many=True)
    ingridients = AmountSerializer(many=True)
    image = Base64ImageField()

    class Meta:
        model = Recipe
        fields = ('id', 'name', 'author', 'image', 'text', 'tags', 'ingridients', 'cooking_time')

    def create(self, validated_data):
        ingridients = validated_data.pop('ingridients') # вырезаем ингридиенты
        tags = validated_data.pop('tags')  # вырезаем теги
        recipe = Recipe.objects.create(**validated_data) # возвращаем модифицированный рецепт
        for value in tags:
            tags_id = value.id
            recipe.tags.add(get_object_or_404(Tags, pk=tags_id))
        return recipe

{
  "name": "test",
  "image": "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIA",
  "author": {
    "email": "test@test.com",
    "username": "string",
    "first_name": "string",
    "last_name": "string"
  },
  "text": "test",
  "tags": [
    1
  ],
  "ingridients": [
    {
      "id": 1,
      "amount": 100
    }
  ],
  "cooking_time": 1
}

Response body
Download
{
  "id": 43,
  "name": "test",
  "author": {
    "email": "test@test.com",
    "id": 1,
    "username": "Soulafein",
    "first_name": "",
    "last_name": "",
    "is_subscribed": false
  },
  "image": "http://127.0.0.1:8000/media/photos/2022/08/22/55896ab9-f57d-4b87-b14f-977188692b3e.jpeg",
  "text": "test",
  "tags": [
    1
  ],
  "ingridients": [],
  "cooking_time": 1
}

{
    "id": 43,
    "ingridients": [],
    "author": {
      "email": "test@test.com",
      "id": 1,
      "username": "Soulafein",
      "first_name": "",
      "last_name": "",
      "is_subscribed": false
    },
    "tags": [
      {
        "id": 1,
        "name": "Завтрак",
        "color": "#761352",
        "slug": "breakfast"
      }
    ],
    "image": "http://127.0.0.1:8000/media/photos/2022/08/22/55896ab9-f57d-4b87-b14f-977188692b3e.jpeg",
    "name": "test",
    "text": "test",
    "cooking_time": 1,
    "is_favorited": false,
    "is_in_shopping_cart": false
  },

1-й скрин это мой код, 2-й и 3-й это то что я передаю/получаю, а 4-й это тот рзультат который мне нужен.
Всем спасибо.
  • Вопрос задан
  • 196 просмотров
Пригласить эксперта
Ответы на вопрос 1
@Soulafein Автор вопроса
def to_representation(self, instance):
        tags = instance.tags.all()
        tags_fields_to_representation = [
            {
                'name': tag.name,
                'color': tag.color,
                'slug': tag.slug
            } for tag in tags]
        representation = super().to_representation(instance)
        if instance.tags:
            representation['tags'] = tags_fields_to_representation
        return representation


Вот такое вышло. Понятно что колхоз, но уже работает )) Спасибо.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы