django-mutant icon indicating copy to clipboard operation
django-mutant copied to clipboard

Working with DRF ?

Open AlexLaur opened this issue 3 years ago • 0 comments

Hi !!

It is more than a question that an issue.

Is it possible to use django-mutant with django rest_framework ?

Indeed, I tried to connect a mutant model with a ModelViewSet and ModelSerializer. It works perfectly. But If I add a new field, I need to restart all the django app in order to see the new field in the next request (e.g : from postman).

I tried lot of aproach

  • Reload the app on change (it is not the best solution and in didn't find a good way to do it)
  • Try to reload urls or routers in order to force the update of Viewset and Serializers...
  • Subclass the ModelViewSet and ModelSerializer in order to dynamically get new fields...

Edit :

I saw that even if I subclass the ModelViewSet and ModelSerializer in order to have a dynamic model, the _meta object inside the model is always the same. (Lot of DRF stuff use _meta in order to get fields...)

Quick and dirty test inside a viewset class:

# Inside TempViewSet wich inherit of viewsets.ModelViewSet
def list(self, *args, **kwargs):
    ct = ModelDefinition.objects.get(object_name="awesome")
    ct_class = ct.model_class()

    print(id(ct_class)) # Always a different object
    print(id(ct_class._meta)) # Always the same object

    self.queryset = ct_class.objects.all()
    return super(TempViewSet, self).list(*args, **kwargs)

When I am in the django shell, all works well:

>>> ct = ModelDefinition.objects.get(model='awesome')
>>> id(ct.model_class()._meta)
>>> 140283303675264

>>> CharFieldDefinition.objects.create(model_def=ct, name='good', max_length=50, null=True, blank=True)
>>> <CharFieldDefinition: CharFieldDefinition object (33)>
>>> id(ct.model_class()._meta)
>>> 140283303675120

I am run out of ideas :/

Any help will be very usefull !

Best regards from France,

AlexLaur avatar Sep 30 '21 21:09 AlexLaur