inmate37
inmate37

Reputation: 1238

Auto add new model_field on request in Django || DRF

I have a simple REST-API project.

Here is my models:

class Human(Model):
    height = IntegerField()

And I have a serializer for that:

class HumanSerializer(ModelSerializer):
    id = IntegerField(read_only=True)
    height = IntegerField(required=True)

Very clear and simple! But! What I want is to be able to add additional fields to my Human model, and automatically migrate those changes to the database, and add a new field to serializer that would be related to the new model field.

For example, lets say that the client want to add a new field called "weight". So a developer won't do anything, because the backend will automatically receive that request, will automatically create a new field to Human model, automatically create a new field to serializer, and automatically create a migration.py file related to those changes.

Is there a way to achieve that ? What is the best way to do that ?

Upvotes: 1

Views: 187

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476709

In case the Human model has no relations (like a ForeignKey, ManyToManyField, OneToOneField, etc.) to models, then you can simply specify this with fields = '__all__':

class HumanSerializer(ModelSerializer):
    class Meta:
        model = Human
        fields = '__all__' 

But relations to other models will still have to be included manually, since there can be several ways to handle this:

  1. by ignoring them;
  2. by adding the id (or URI) to the object;
  3. by serializing the related objects as well;
  4. ...

Perhaps serializing the related objects looks like a straightforward choice, but this can result in infinite recursion if for example an object (perhaps indirectly) points to itself, so that would mean that the serialization of that objects contains the serialization of that object. Even if it does not create recursive loops, it can still blow up the response gigantically, so even if this recursion is not possible, it might not be ideal to transfer thousands of objects in a single response. Finally a reason why this might not be advisable is that through those relations, we might end up into models that store sensitive information (for example if an object is linked to a model that is linked to one or more users, then your API would expose details of the users), which might not be a good idea.

If for example Human would have a reference to a (hypothetical) Ssn object, then you can serialize this as well with:

class HumanSerializer(ModelSerializer):
    ssn = SsnSerializer(read_only=True)

    class Meta:
        model = Human
        fields = '__all__'

Upvotes: 2

Related Questions