Include preferences in users returned by user API

This commit is contained in:
Greg Price
2014-03-05 14:09:27 -05:00
parent 601b5a8ceb
commit 8f01756c6c
4 changed files with 22 additions and 4 deletions

View File

@@ -4,7 +4,7 @@ from django.db import models
class UserPreference(models.Model):
"""A user's preference, stored as generic text to be processed by client"""
user = models.ForeignKey(User, db_index=True, related_name="+")
user = models.ForeignKey(User, db_index=True, related_name="preferences")
key = models.CharField(max_length=255, db_index=True)
value = models.TextField()

View File

@@ -6,15 +6,19 @@ from user_api.models import UserPreference
class UserSerializer(serializers.HyperlinkedModelSerializer):
name = serializers.SerializerMethodField("get_name")
preferences = serializers.SerializerMethodField("get_preferences")
def get_name(self, user):
profile = UserProfile.objects.get(user=user)
return profile.name
def get_preferences(self, user):
return dict([(pref.key, pref.value) for pref in user.preferences.all()])
class Meta:
model = User
# This list is the minimal set required by the notification service
fields = ("id", "email", "name", "username")
fields = ("id", "email", "name", "username", "preferences")
read_only_fields = ("id", "email", "username")

View File

@@ -66,7 +66,11 @@ class ApiTestCase(TestCase):
def assertUserIsValid(self, user):
"""Assert that the given user result is valid"""
self.assertItemsEqual(user.keys(), ["email", "id", "name", "username", "url"])
self.assertItemsEqual(user.keys(), ["email", "id", "name", "username", "preferences", "url"])
self.assertItemsEqual(
user["preferences"].items(),
[(pref.key, pref.value) for pref in self.prefs if pref.user.id == user["id"]]
)
self.assertSelfReferential(user)
def assertPrefIsValid(self, pref):
@@ -221,6 +225,11 @@ class UserViewSetTest(UserApiTestCase):
"id": user.id,
"name": user.profile.name,
"username": user.username,
"preferences": dict([
(user_pref.key, user_pref.value)
for user_pref in self.prefs
if user_pref.user == user
]),
"url": uri
}
)
@@ -352,6 +361,11 @@ class UserPreferenceViewSetTest(UserApiTestCase):
"id": pref.user.id,
"name": pref.user.profile.name,
"username": pref.user.username,
"preferences": dict([
(user_pref.key, user_pref.value)
for user_pref in self.prefs
if user_pref.user == pref.user
]),
"url": self.get_uri_for_user(pref.user),
},
"key": pref.key,

View File

@@ -28,7 +28,7 @@ class ApiKeyHeaderPermission(permissions.BasePermission):
class UserViewSet(viewsets.ReadOnlyModelViewSet):
authentication_classes = (authentication.SessionAuthentication,)
permission_classes = (ApiKeyHeaderPermission,)
queryset = User.objects.all()
queryset = User.objects.all().prefetch_related("preferences")
serializer_class = UserSerializer
paginate_by = 10
paginate_by_param = "page_size"