Monday, 15 March 2010

python - Django Rest Framework: best way to populate field manually -



python - Django Rest Framework: best way to populate field manually -

considering next model:

class request(models.model): user = models.foreignkey('user', related_name='requests')

and viewset create/update:

class requestviewset(mixins.createmodelmixin, mixins.updatemodelmixin, viewsets.genericviewset):

i want set user on create , not on update

first solution:

class requestviewset(mixins.createmodelmixin, mixins.updatemodelmixin, viewsets.genericviewset): def pre_save(self, obj): create = false try: if not obj.user: create = true except objectdoesnotexist: create = true if create: obj.user = self.request.user

second solution using restore_object:

class requestserializer(serializers.modelserializer): def restore_object(self, attrs, instance=none): create = not instance instance = super(requestserializer, self).restore_object(attrs, instance) if create: request = self.context['request'] instance.user = request.user homecoming instance

what's more logical? tend prefer first 1 (except try/except find no alternative it)

i'm not big fan of class based views, prefer fat models , lean views.

i opt post_save signal on request , check created param.

https://docs.djangoproject.com/en/dev/ref/signals/#post-save

request(...): @classmethod def post_save(cls, sender, instance, created, raw, **kwargs): if raw: homecoming if created: pass # on create stuff here post_save.connect(request.post_save, sender=request, dispatch_uid="uniqueid") # utilize weak=false if utilize local function

also note instance.save() triggers save signals again, might consider utilize .update() if want avoid signals processed 1 time again (or worse, create signal loop ;-) )

python django django-rest-framework

No comments:

Post a Comment