python - Django Restframework: update an object without accesing specific object id -
i using django restframework, , want update object. have following model:
class promotionalcode(models.model): promotional_code = models.charfield(max_length=10, default=random_with_letters(), unique=true) myuser = models.foreignkey('myuser', related_name='promotional_code_user', blank=true, null=true) promotion_type = models.positiveintegerfield(default=1) time_transaction = models.datetimefield(default=datetime.now()) used = models.booleanfield(default=false) the following viewset:
class updateonlydetailviewset(mixins.updatemodelmixin, viewsets.genericviewset): pass the following view:
class promotionalcodeviewset(updateonlydetailviewset): queryset = promotionalcode.objects.all() serializer_class = promotionalcodeserializer permission_classes = (isownerorreadonly,) and has following url:
router = defaultrouter() router.register(r'promotionalcode', views.promotionalcodeviewset) i can update promotionalcode object when access
/promotionalcode/code_id
and want update code when access
/promotionalcode/
without specifying id. have do it?
i have found 3 solutions problem. have tested 2 of them:
first solution: have created model called
promotionalcodeshistory(models.model)same attributespromotionalcode, create serializer method create, creatingpromotionalcodeshistoryinstance , call update method updatepromotionalcode. then, when access url/promotional/can update promotional code.second solution: modify
defaultrouter()access update on/promotional/url, following code:
from rest_framework.routers import defaultrouter class customupdaterouter(defaultrouter): routes = [ # list route. route( url=r'^{prefix}{trailing_slash}$', mapping={ 'get': 'list', 'post': 'create', 'put': 'update', 'patch': 'partial_update', }, name='{basename}-list', initkwargs={'suffix': 'list'} ), # dynamically generated list routes. # generated using @list_route decorator # on methods of viewset. dynamiclistroute( url=r'^{prefix}/{methodname}{trailing_slash}$', name='{basename}-{methodnamehyphen}', initkwargs={} ), # detail route. route( url=r'^{prefix}/{lookup}{trailing_slash}$', mapping={ 'get': 'retrieve', 'delete': 'destroy' }, name='{basename}-detail', initkwargs={'suffix': 'instance'} ), # dynamically generated detail routes. # generated using @detail_route decorator on methods of viewset. dynamicdetailroute( url=r'^{prefix}/{lookup}/{methodname}{trailing_slash}$', name='{basename}-{methodnamehyphen}', initkwargs={} ), ] then, on view class, reimplement get_object method specify own filters object, can access get_serializer_context method context data, filter specified using dictionary of unicode, following:
{u'key': unicode(variable1), u'key2': unicode(variable2)} - third solution: last solution have not tested, change primary key
promotional_codefield, access promotional code, using/promotionalcode/promotional_code
Comments
Post a Comment