Skip to content

Instantly share code, notes, and snippets.

@svvitale
Last active August 29, 2015 14:15
Show Gist options
  • Save svvitale/d5aabb6f4cc805bb4d05 to your computer and use it in GitHub Desktop.
Save svvitale/d5aabb6f4cc805bb4d05 to your computer and use it in GitHub Desktop.
Comprehensions or Loops?
def get(self, request):
return {
"rooms": [
{attrName: attrVal for attrName, attrVal in model_to_dict(x).items()
if attrName in RoomView.ROOM_PUBLIC_FIELDS}
for x in Room.objects.all()
]
}
# Only these fields will be returned by API calls
ROOM_PUBLIC_FIELDS = [
'id',
'name'
]
@staticmethod
def filter_room_fields(room_obj):
return {attrName: attrVal for attrName, attrVal in model_to_dict(room_obj).items()
if attrName in RoomView.ROOM_PUBLIC_FIELDS}
@json
def get(self, request, room_id=None):
if room_id:
return RoomView.filter_room_fields(Room.objects.get(id=room_id))
else:
return {
"rooms": [RoomView.filter_room_fields(room_obj) for room_obj in Room.objects.all()]
}
def get(self, request):
result = {"rooms": []}
for current_room in Room.objects.all():
current_room_data = {}
for attrName, attrVal in model_to_dict(current_room).items():
if attrName in RoomView.ROOM_PUBLIC_FIELDS:
current_room_data[attrName] = attrVal
result["rooms"].append(current_room_data)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment