0

Let's say I have the following:

class EntityManager(Manager):
 def create(label, entity_type, **kwargs):
    ... do stuff with label and entity type
    obj = super().create(**cleanedupkwargs)
    obj.addstuffwithlabel(label)
    return obj

class Entity(Model):
 somefields...

 objects = EntityManager()

There's no problem with this and I can call Entity.objects.create(label='foo', entity_type=my_entity_type, other_params=foo)

the issue is I'm now using a serializer and I tried this

class EntityBareboneSerializer(serializers.ModelSerializer):
label = serializers.SerializerMethodField()
entity_type = serializers.SerializerMethodField()

class Meta:
    model = Entity
    fields = [
        'id',
        'label',
        'entity_type',
    ]

def validate_label(self, label):
    return label

def validate_entity_type(self, entity_type):
    return entity_type

def create(self, validated_data):
    # do stuff with label and entity type
    return Entity.objects.create(**validated_data)

The issue is when is_valid is called the validated_data param comes back empty.

Any idea if it's possible to effectively use my custom create method in the serializer?

Stupid.Fat.Cat
  • 10,755
  • 23
  • 83
  • 144

1 Answers1

0

You can pre-process the validated data, before creating an instance

    def create(self, validated_data):
        label = validated_data.pop("label", "some_default_value")
        entity_type = validated_data.pop("entity_type", "some_default_value")
        obj = Entity.objects.create(**validated_data)
        obj.addstuffwithlabel(label)
        return obj
Icebreaker454
  • 1,031
  • 7
  • 12
  • The issue is less the create call and moreso the required `is_valid` call. – Stupid.Fat.Cat Mar 30 '21 at 18:32
  • Just to clarify the issue. this won't work as label isn't a "valid field" when the serializer tries to validate the data it'll error out before the create call is called. – Stupid.Fat.Cat Mar 30 '21 at 19:39
  • In that case, why don't you add your `label` and `entity_type` to the serializer fields ? You can add any additional fields to your serializer - https://stackoverflow.com/questions/18396547/django-rest-framework-adding-additional-field-to-modelserializer – Icebreaker454 Mar 30 '21 at 20:40
  • Ah that does sorta work but then the when I call the is_valid method all of my input fields disappear resulting in an empty dictionary. – Stupid.Fat.Cat Mar 31 '21 at 20:06