Fix kwargs in url conf to be more consistent, also fixes broken blog posts example (every blog post showed all comments)

This commit is contained in:
tom christie tom@tomchristie.com 2011-02-19 17:55:32 +00:00
parent 38c6a37af7
commit 67c48f758f
3 changed files with 14 additions and 5 deletions

View File

@ -1,6 +1,7 @@
from django.forms import ModelForm
from django.db.models.query import QuerySet
from django.db.models import Model
from django.db.models.query import QuerySet
from django.db.models.fields.related import RelatedField
from djangorestframework.response import Response, ResponseException
from djangorestframework.resource import Resource
@ -340,6 +341,13 @@ class ModelResource(Resource, ModelFormValidatorMixin):
def post(self, request, auth, content, *args, **kwargs):
# TODO: test creation on a non-existing resource url
# translated related_field into related_field_id
for related_name in [field.name for field in self.model._meta.fields if isinstance(field, RelatedField)]:
if kwargs.has_key(related_name):
kwargs[related_name + '_id'] = kwargs[related_name]
del kwargs[related_name]
all_kw_args = dict(content.items() + kwargs.items())
if args:
instance = self.model(pk=args[-1], **all_kw_args)
@ -373,6 +381,7 @@ class ModelResource(Resource, ModelFormValidatorMixin):
else:
# Otherwise assume the kwargs uniquely identify the model
instance = self.model.objects.get(**kwargs)
for (key, val) in content.items():
setattr(instance, key, val)
except self.model.DoesNotExist:
@ -404,7 +413,7 @@ class RootModelResource(ModelResource):
def get(self, request, auth, *args, **kwargs):
queryset = self.queryset if self.queryset else self.model.objects.all()
return queryset
return queryset.filter(**kwargs)
class QueryModelResource(ModelResource):
@ -418,5 +427,5 @@ class QueryModelResource(ModelResource):
def get(self, request, auth, *args, **kwargs):
queryset = self.queryset if self.queryset else self.model.objects.all()
return queryset
return queryset.filer(**kwargs)

View File

@ -30,7 +30,7 @@ class BlogPost(models.Model):
@models.permalink
def comments_url(self):
"""Link to a resource which lists all comments for this blog post."""
return ('comments', (), {'blogpost_id': self.key})
return ('comments', (), {'blogpost': self.key})
def __unicode__(self):
return self.title

View File

@ -4,6 +4,6 @@ from blogpost.views import BlogPosts, BlogPostInstance, Comments, CommentInstanc
urlpatterns = patterns('',
url(r'^$', BlogPosts.as_view(), name='blog-posts'),
url(r'^(?P<key>[^/]+)/$', BlogPostInstance.as_view(), name='blog-post'),
url(r'^(?P<blogpost_id>[^/]+)/comments/$', Comments.as_view(), name='comments'),
url(r'^(?P<blogpost>[^/]+)/comments/$', Comments.as_view(), name='comments'),
url(r'^(?P<blogpost>[^/]+)/comments/(?P<id>[^/]+)/$', CommentInstance.as_view(), name='comment'),
)