0

I have a serializer

class MappingSerializer(ExtendedModelSerializer):
    default_landing_page_url = serializers.URLField(read_only=True)

    class Meta:
        model = models.Mapping
        fields = ('id', 'name', 'settings', 'campaign','default_landing_page_url')

    def create(self, validated_data):
        instance = super().create(validated_data)
        profile_id = instance.settings.integration.profile_id
        instance.default_landing_page_url = helpers.get_landing_page_url(profile_id, instance.campaign)
        instance.save()
        return instance

In this case, there is a 2 queries into db,first when calling super().create(validated_data) and second is instance.save(). How can I avoid doing 2 queries with the same logic.

I could add extra field validated["default_landing_page_url"] = helpers.get_landing_page_url(profile_id, instance.campaign) and then call super().create() but in this case I can't reach profile_id, which can be accessible only after instance is created

uchiha itachi
  • 195
  • 11
  • I don't think this question can be answered without knowing where `settings.integration.profile_id` comes from. – Tom Wojcik Mar 19 '21 at 08:47
  • Mapping object has fk relation to Setting model. Which has fk to Integration model. Which has profile_id field – uchiha itachi Mar 19 '21 at 08:49
  • How are you creating this `integration` object, is it some logic in the model's `save()` function? Is the Mapping object's `id` required for figuring out the `profile_id`? If so, you're out of luck probably, because you must save the instance into database before you know its id. And if not, you simply must put the logic for figuring out `profile_id` before the `super().create`, like you said. – Raekkeri Mar 19 '21 at 08:50
  • > I can't reach profile_id, which can be accessible only after instance is created - If so, then I don't think it's possible. Remeber to wrap it with `transaction.atomic`. Maybe show what's exactly in the `validated_data`. I'm under the impression that `settings` exists before creating `instance`. – Tom Wojcik Mar 19 '21 at 08:53

1 Answers1

1

I think you will find an answer on your question here :Editing django-rest-framework serializer object before save it looks like the same problem.