Commits

Martin Skala committed 6fe4eaa

Switchover from ids to pks

  • Participants
  • Parent commits c3cff89

Comments (0)

Files changed (4)

examples/django_roa_client/models.py

     title = models.CharField(max_length=50, blank=True, null=True)
     
     def __unicode__(self):
-        return u'%s (%s)' % (self.title, self.id)
+        return u'%s (%s)' % (self.title, self.pk)
 
     @staticmethod
     def get_resource_url_list():
     image_field = models.ImageField(upload_to="images", blank=True, null=True)
     
     def __unicode__(self):
-        return u'%s (%s)' % (self.__class__.__name__, self.id)
+        return u'%s (%s)' % (self.__class__.__name__, self.pk)
 
     @staticmethod
     def get_resource_url_list():
     slug = models.SlugField()
     
     def __unicode__(self):
-        return u'%s (%s)' % (self.title, self.id)
+        return u'%s (%s)' % (self.title, self.pk)
 
     def save(self, force_insert=False, force_update=False, using=None):
         if not self.slug:
         return u'http://127.0.0.1:8081/django_roa_server/remotepagewithcustomslug/'
 
     def get_resource_url_detail(self):
-        return u"%s%s-%s/" % (self.get_resource_url_list(), self.id, self.slug)
+        return u"%s%s-%s/" % (self.get_resource_url_list(), self.pk, self.slug)
 
 
 class RemotePageWithOverriddenUrls(Model):
     slug = models.SlugField()
 
     def __unicode__(self):
-        return u'%s (%s)' % (self.title, self.id)
+        return u'%s (%s)' % (self.title, self.pk)
 
     def save(self, force_insert=False, force_update=False, using=None):
         if not self.slug:
     remote_page_with_many_fields = models.ForeignKey("RemotePageWithManyFields", blank=True, null=True)
 
     def __unicode__(self):
-        return u'%s (%s)' % (self.title, self.id)
+        return u'%s (%s)' % (self.title, self.pk)
     
     @staticmethod
     def get_resource_url_list():
     remote_page_fields = models.ManyToManyField(RemotePageWithManyFields, through=RemotePageWithRelationsThrough, blank=True, null=True)
 
     def __unicode__(self):
-        return u'%s (%s)' % (self.title, self.id)
+        return u'%s (%s)' % (self.title, self.pk)
     
     @staticmethod
     def get_resource_url_list():
     last_page = models.ForeignKey(RemotePage, blank=True, null=True, related_name="from_last")
 
     def __unicode__(self):
-        return u'%s (%s)' % (self.title, self.id)
+        return u'%s (%s)' % (self.title, self.pk)
     
     @staticmethod
     def get_resource_url_list():

examples/django_roa_server/handlers.py

 
     def flatten_dict(self, dct):
         return dict([ (str(k), dct.get(k)) for k in dct.keys() \
-            if (k, dct.get(k)) != (u'id', u'None')])
+            if (k, dct.get(k)) != (u'id', u'None') and (k, dct.get(k)) != (u'pk', u'None')])
 
     @staticmethod
     def _get_object(model, *args, **kwargs):
-        return get_object_or_404(model, id=kwargs['id'])
-        
+        return get_object_or_404(model, pk=kwargs['pk'])
+
     def read(self, request, *args, **kwargs):
         """
         Retrieves an object or a list of objects.
         """
         if not self.has_model():
             return rc.NOT_IMPLEMENTED
-        
+
         logger.debug('Args: %s' % str(args))
         logger.debug('Kwargs: %s' % str(kwargs))
-        
+
         if kwargs.values() != [None]:
             # Returns a single object
             return [self._get_object(self.model, *args, **kwargs)]
-        
+
         # Initialization
         queryset = _get_queryset(self.model)
         logger.debug('Before filters: %s' % str(queryset))
-        
+
         # Filtering
         filters, excludes = {}, {}
         for k, v in request.GET.iteritems():
             if k.startswith('exclude_'):
                 excludes[k[8:]] = v
         queryset = queryset.filter(*filters.items()).exclude(*excludes.items())
-        
+
         logger.debug('Filters: %s' % str(filters))
         logger.debug('Excludes: %s' % str(excludes))
         logger.debug('After filters: %s' % str(queryset))
-        
+
         # Ordering (test custom parameters' name)
         if 'order' in request.GET:
             order_bys = request.GET['order'].split(',')
             queryset = queryset.order_by(*order_bys)
-        
+
         # Slicing
         limit_start = int(request.GET.get('limit_start', 0))
         limit_stop = request.GET.get('limit_stop', False) and int(request.GET['limit_stop']) or None
         queryset = queryset[limit_start:limit_stop]
-        
+
         obj_list = list(queryset)
         if not obj_list:
             raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
         logger.debug(u'Objects: %s retrieved' % [unicode(obj) for obj in obj_list])
         return queryset
-        
+
     def create(self, request, *args, **kwargs):
         """
         Creates an object given request args, returned as a list.
         """
         if not self.has_model():
             return rc.NOT_IMPLEMENTED
-        
+
         data = request.POST.copy()
-        
+
         values = {}
         for field in self.model._meta.local_fields:
             field_value = data.get(field.name, None)
-            
+
             if field_value not in (u'', u'None'):
-                
+
                 # Handle FK fields
                 if field.rel and isinstance(field.rel, models.ManyToOneRel):
                     field_value = data.get(field.attname, None)
                         values[field.attname] = field.rel.to._meta.get_field(field.rel.field_name).to_python(field_value)
                     else:
                         values[field.attname] = None
-                
+
                 # Handle all other fields
                 else:
                     if isinstance(field, models.fields.BooleanField):
                     values[field.name] = field_value
 
         obj = self.model.objects.create(**values)
-        
-        response = [self.model.objects.get(id=obj.id)]
+
+        response = [self.model.objects.get(pk=obj.pk)]
         logger.debug(u'Object "%s" created' % unicode(obj))
         return response
 
         """
         if not self.has_model():
             return rc.NOT_IMPLEMENTED
-        
+
         data = request.PUT.copy()
         logger.debug(u'Received: %s as PUT data' % data)
         obj = self._get_object(self.model, *args, **kwargs)
-        
+
         for field in self.model._meta.local_fields:
             field_name = field.name
-            
+
             # Handle FK fields
             if field.rel and isinstance(field.rel, models.ManyToOneRel):
                 field_value = data.get(field.attname, None)
                 else:
                     field_value = None
                 setattr(obj, field.attname, field_value)
-            
+
             # Handle all other fields
             elif field_name in data:
                 field_value = data[field_name]
                     if field_value is None:
                         field_value = u''
                 setattr(obj, field_name, field_value)
-        
+
         obj.save()
-        
-        response = [self.model.objects.get(id=obj.id)]
+
+        response = [self.model.objects.get(pk=obj.pk)]
         logger.debug(u'Object "%s" modified with %s' % (
             unicode(obj), unicode(data.items())))
         return response
         """
         if not self.has_model():
             raise NotImplementedError
-        
+
         try:
             obj = self._get_object(self.model, *args, **kwargs)
             obj.delete()
         """
         if not self.has_model():
             return rc.NOT_IMPLEMENTED
-        
+
         # Initialization
         queryset = _get_queryset(self.model)
-        
+
         # Filtering
         filters, excludes = {}, {}
         for k, v in request.GET.iteritems():
             if k.startswith('exclude_'):
                 excludes[k[8:]] = v
         queryset = queryset.filter(*filters.items()).exclude(*excludes.items())
-        
+
         # Ordering
         if 'order_by' in request.GET:
             order_bys = request.GET['order_by'].split(',')
             queryset = queryset.order_by(*order_bys)
-        
+
         # Counting
         counter = queryset.count()
         logger.debug(u'Count: %s objects' % counter)
 
 
 class ROAWithSlugHandler(ROAHandler):
-    
+
     @staticmethod
     def _get_object(model, *args, **kwargs):
         """Returns an object from a slug.
-        
+
         Useful when the slug is a combination of many fields.
         """
         pk, slug = kwargs['object_slug'].split('-', 1)
-        obj = get_object_or_404(model, id=pk)
+        obj = get_object_or_404(model, pk=pk)
         return obj
 
 

examples/django_roa_server/models.py

     title = models.CharField(max_length=50, blank=True, null=True)
 
     def __unicode__(self):
-        return u'%s (%s)' % (self.title, self.id)
+        return u'%s (%s)' % (self.title, self.pk)
 
 
 class RemotePageWithManyFields(models.Model):
     image_field = models.ImageField(upload_to="images", blank=True, null=True)
     
     def __unicode__(self):
-        return u'%s (%s)' % (self.__class__.__name__, self.id)
+        return u'%s (%s)' % (self.__class__.__name__, self.pk)
 
 
 class RemotePageWithBooleanFields(models.Model):
     slug = models.SlugField()
     
     def __unicode__(self):
-        return u'%s (%s)' % (self.title, self.id)
+        return u'%s (%s)' % (self.title, self.pk)
 
 
 class RemotePageWithOverriddenUrls(models.Model):
     slug = models.SlugField()
     
     def __unicode__(self):
-        return u'%s (%s)' % (self.title, self.id)
+        return u'%s (%s)' % (self.title, self.pk)
 
 
 class RemotePageWithRelationsThrough(models.Model):
     remote_page_with_many_fields = models.ForeignKey("RemotePageWithManyFields", blank=True, null=True)
 
     def __unicode__(self):
-        return u'%s (%s)' % (self.title, self.id)
+        return u'%s (%s)' % (self.title, self.pk)
 
 
 class RemotePageWithRelations(models.Model):
     remote_page_fields = models.ManyToManyField(RemotePageWithManyFields, through=RemotePageWithRelationsThrough, blank=True, null=True)
 
     def __unicode__(self):
-        return u'%s (%s)' % (self.title, self.id)
+        return u'%s (%s)' % (self.title, self.pk)
 
 
 class RemotePageWithNamedRelations(models.Model):
     last_page = models.ForeignKey(RemotePage, blank=True, null=True, related_name="from_last")
 
     def __unicode__(self):
-        return u'%s (%s)' % (self.title, self.id)
+        return u'%s (%s)' % (self.title, self.pk)

examples/django_roa_server/urls.py

     url(r'^django_roa_server/remotepagewithproxy/count/$', remote_pages_count),
     
     # Remote pages
-    url(r'^django_roa_server/remotepage/?(?P<id>\d+)?/?$', remote_pages),
-    url(r'^django_roa_server/remotepagewithmanyfields/?(?P<id>\d+)?/?$', remote_pages_with_many_fields),
-    url(r'^django_roa_server/remotepagewithbooleanfields/?(?P<id>\d+)?/?$', remote_pages_with_boolean_fields),
+    url(r'^django_roa_server/remotepage/?(?P<pk>\d+)?/?$', remote_pages),
+    url(r'^django_roa_server/remotepagewithmanyfields/?(?P<pk>\d+)?/?$', remote_pages_with_many_fields),
+    url(r'^django_roa_server/remotepagewithbooleanfields/?(?P<pk>\d+)?/?$', remote_pages_with_boolean_fields),
     url(r'^django_roa_server/remotepagewithcustomslug/?(?P<object_slug>[-\w]+)?/?$', remote_pages_with_custom_slug),
     url(r'^django_roa_server/remotepagewithoverriddenurls/?(?P<object_slug>[-\w]+)?/?$', remote_pages_with_overridden_urls),
-    url(r'^django_roa_server/remotepagewithrelations/?(?P<id>\d+)?/?$', remote_pages_with_relations),
-    url(r'^django_roa_server/remotepagewithrelationsthrough/?(?P<id>\d+)?/?$', remote_pages_with_relations_through),
-    url(r'^django_roa_server/remotepagewithnamedrelations/?(?P<id>\d+)?/?$', remote_pages_with_named_relations),
-    url(r'^django_roa_server/remotepagewithproxy/?(?P<id>\d+)?/?$', remote_pages),
+    url(r'^django_roa_server/remotepagewithrelations/?(?P<pk>\d+)?/?$', remote_pages_with_relations),
+    url(r'^django_roa_server/remotepagewithrelationsthrough/?(?P<pk>\d+)?/?$', remote_pages_with_relations_through),
+    url(r'^django_roa_server/remotepagewithnamedrelations/?(?P<pk>\d+)?/?$', remote_pages_with_named_relations),
+    url(r'^django_roa_server/remotepagewithproxy/?(?P<pk>\d+)?/?$', remote_pages),
     
     # Auth application
-    url(r'^auth/user/?(?P<id>\d+)?/?$', users),
-    url(r'^auth/message/?(?P<id>\d+)?/?$', messages),
-    url(r'^auth/permission/?(?P<id>\d+)?/?$', permissions),
-    url(r'^auth/group/?(?P<id>\d+)?/?$', groups),
+    url(r'^auth/user/?(?P<pk>\d+)?/?$', users),
+    url(r'^auth/message/?(?P<pk>\d+)?/?$', messages),
+    url(r'^auth/permission/?(?P<pk>\d+)?/?$', permissions),
+    url(r'^auth/group/?(?P<pk>\d+)?/?$', groups),
 )