class IprDisclosureBaseResource(ModelResource): by = ToOneField(PersonResource, 'by') state = ToOneField(IprDisclosureStateNameResource, 'state') docs = ToManyField(DocAliasResource, 'docs', null=True) rel = ToManyField('ietf.ipr.resources.IprDisclosureBaseResource', 'rel', null=True) class Meta: queryset = IprDisclosureBase.objects.all() cache = SimpleCache() serializer = api.Serializer() #resource_name = 'iprdisclosurebase' filtering = { "id": ALL, "compliant": ALL, "holder_legal_name": ALL, "notes": ALL, "other_designations": ALL, "submitter_name": ALL, "submitter_email": ALL, "time": ALL, "title": ALL, "by": ALL_WITH_RELATIONS, "state": ALL_WITH_RELATIONS, "docs": ALL_WITH_RELATIONS, "rel": ALL_WITH_RELATIONS, }
def test_dehydrate_with_callable(self): # note = Note() bundle_1 = Bundle(obj=self.note_2) field_1 = ToManyField(SubjectResource, attribute=lambda bundle: Subject.objects.filter(notes=bundle.obj, name__startswith='Personal')) field_1.instance_name = 'm2m' self.assertEqual(field_1.dehydrate(bundle_1), ['/api/v1/subjects/3/'])
class GenericIprDisclosureResource(ModelResource): by = ToOneField(PersonResource, 'by') state = ToOneField(IprDisclosureStateNameResource, 'state') iprdisclosurebase_ptr = ToOneField(IprDisclosureBaseResource, 'iprdisclosurebase_ptr') docs = ToManyField(DocAliasResource, 'docs', null=True) rel = ToManyField(IprDisclosureBaseResource, 'rel', null=True) class Meta: cache = SimpleCache() queryset = GenericIprDisclosure.objects.all() serializer = api.Serializer() #resource_name = 'genericiprdisclosure' filtering = { "id": ALL, "compliant": ALL, "holder_legal_name": ALL, "notes": ALL, "other_designations": ALL, "submitter_name": ALL, "submitter_email": ALL, "time": ALL, "title": ALL, "holder_contact_name": ALL, "holder_contact_email": ALL, "holder_contact_info": ALL, "statement": ALL, "by": ALL_WITH_RELATIONS, "state": ALL_WITH_RELATIONS, "iprdisclosurebase_ptr": ALL_WITH_RELATIONS, "docs": ALL_WITH_RELATIONS, "rel": ALL_WITH_RELATIONS, }
class PolicyResource(FootprintResource): policies = ToManyField('self', 'policies') tags = ToManyField(TagResource, 'tags') class Meta: always_return_data = True queryset = Policy.objects.all()
class LiaisonStatementResource(ModelResource): from_contact = ToOneField(EmailResource, 'from_contact', null=True) purpose = ToOneField(LiaisonStatementPurposeNameResource, 'purpose') state = ToOneField(LiaisonStatementStateResource, 'state') from_groups = ToManyField(GroupResource, 'from_groups', null=True) to_groups = ToManyField(GroupResource, 'to_groups', null=True) tags = ToManyField(LiaisonStatementTagNameResource, 'tags', null=True) attachments = ToManyField(DocumentResource, 'attachments', null=True) class Meta: cache = SimpleCache() queryset = LiaisonStatement.objects.all() serializer = api.Serializer() #resource_name = 'liaisonstatement' filtering = { "id": ALL, "title": ALL, "to_contacts": ALL, "response_contacts": ALL, "technical_contacts": ALL, "action_holder_contacts": ALL, "cc_contacts": ALL, "deadline": ALL, "other_identifiers": ALL, "body": ALL, "from_name": ALL, "to_name": ALL, "from_contact": ALL_WITH_RELATIONS, "purpose": ALL_WITH_RELATIONS, "state": ALL_WITH_RELATIONS, "from_groups": ALL_WITH_RELATIONS, "to_groups": ALL_WITH_RELATIONS, "tags": ALL_WITH_RELATIONS, "attachments": ALL_WITH_RELATIONS, }
class TagResource(ModelResource): artists = ToManyField('repertoire.api.resources.ArtistResource', 'artist_set', blank=True, null=True) albums = ToManyField('repertoire.api.resources.AlbumResource', 'album_set', blank=True, null=True) songs = ToManyField('repertoire.api.resources.SongResource', 'track_set', blank=True, null=True) playlists = ToManyField('repertoire.api.resources.PlaylistResource', 'playlist_set', blank=True, null=True) class Meta: queryset = Tag.objects.all() allowed_methods = ['get', 'post', 'put', 'delete'] authentication = MultiAuthentication( BasicAuthentication(realm="Open Sound Stream: TagResource"), ApiKeyOnlyAuthentication()) authorization = UserObjectsOnlyAuthorization() always_return_data = True excludes = ['user'] def obj_create(self, bundle, **kwargs): return super(TagResource, self).obj_create(bundle, user=bundle.request.user)
class PlaylistResource(ModelResource): tags = ToManyField( TagResource, attribute=lambda bundle: Tag.objects.filter(playlist=bundle.obj), blank=True, null=True, full=True, full_detail=True, full_list=False) songsinplaylist = ToManyField(SongInPlaylistResource, 'trackinplaylist_set', blank=True, null=True, full=True, full_detail=True, full_list=True) class Meta: queryset = Playlist.objects.all() allowed_methods = ['get', 'post', 'put', 'delete'] authentication = MultiAuthentication( BasicAuthentication(realm="Open Sound Stream: PlaylistResource"), ApiKeyOnlyAuthentication()) authorization = UserObjectsOnlyAuthorization() always_return_data = True excludes = ['user'] def obj_create(self, bundle, **kwargs): return super(PlaylistResource, self).obj_create(bundle, user=bundle.request.user)
class RoomResource(ModelResource): meeting = ToOneField(MeetingResource, 'meeting') resources = ToManyField(ResourceAssociationResource, 'resources', null=True) session_types = ToManyField(TimeSlotTypeNameResource, 'session_types', null=True) floorplan = ToOneField(FloorPlanResource, 'floorplan', null=True) class Meta: cache = SimpleCache() queryset = Room.objects.all() serializer = api.Serializer() #resource_name = 'room' filtering = { "id": ALL, "name": ALL, "time": ALL, "functional_name": ALL, "capacity": ALL, "meeting": ALL_WITH_RELATIONS, "resources": ALL_WITH_RELATIONS, "session_types": ALL_WITH_RELATIONS, "floorplan": ALL_WITH_RELATIONS, }
class GroupHistoryResource(ModelResource): state = ToOneField(GroupStateNameResource, 'state', null=True) type = ToOneField(GroupTypeNameResource, 'type', null=True) parent = ToOneField(GroupResource, 'parent', null=True) ad = ToOneField(PersonResource, 'ad', null=True) group = ToOneField(GroupResource, 'group') unused_states = ToManyField('ietf.doc.resources.StateResource', 'unused_states', null=True) unused_tags = ToManyField(DocTagNameResource, 'unused_tags', null=True) class Meta: cache = SimpleCache() queryset = GroupHistory.objects.all() serializer = api.Serializer() #resource_name = 'grouphistory' filtering = { "id": ALL, "time": ALL, "name": ALL, "description": ALL, "list_email": ALL, "list_subscribe": ALL, "list_archive": ALL, "comments": ALL, "acronym": ALL, "state": ALL_WITH_RELATIONS, "type": ALL_WITH_RELATIONS, "parent": ALL_WITH_RELATIONS, "ad": ALL_WITH_RELATIONS, "group": ALL_WITH_RELATIONS, "unused_states": ALL_WITH_RELATIONS, "unused_tags": ALL_WITH_RELATIONS, }
def test_traversed_attribute_dehydrate(self): mediabit = MediaBit(id=1, note=self.note_1) bundle = Bundle(obj=mediabit) field_1 = ToManyField(SubjectResource, 'note__subjects') field_1.instance_name = 'm2m' self.assertEqual(field_1.dehydrate(bundle), ['/api/v1/subjects/1/', '/api/v1/subjects/2/']) field_2 = ToOneField(SubjectResource, 'fakefield__subjects') field_2.instance_name = 'm2m' self.assertRaises(ApiFieldError, field_2.hydrate, bundle)
class MailTriggerResource(ModelResource): to = ToManyField(RecipientResource, 'to', null=True) cc = ToManyField(RecipientResource, 'cc', null=True) class Meta: cache = SimpleCache() queryset = MailTrigger.objects.all() #resource_name = 'mailtrigger' filtering = { "slug": ALL, "desc": ALL, "to": ALL_WITH_RELATIONS, "cc": ALL_WITH_RELATIONS, }
class BillResource(ModelResource): call = ToManyField('bills.api.resources.CallResource', 'call', full=True, null=True) booster = ToManyField('bills.api.resources.BoosterResource', 'booster', full=True, null=True) data = ToManyField('bills.api.resources.DataResource', 'data', full=True, null=True) roaming = ToManyField('bills.api.resources.RoamingResource', 'roaming', full=True, null=True) subscriber = ToOneField(SubscriberResource, 'subscriber', full=False, null=True) plan = ToOneField(PlanResource, 'plan', full=False, null=True) class Meta: queryset = Bill.objects.all() resource_name = 'bill' authorization = Authorization() authentication = Authentication() cache = SimpleCache(timeout=1000)
class QueryResource(ModelResource): sample = CharField(attribute='sample', readonly=True, null=True, help_text="sample of the data returned") num_records = IntegerField(attribute='num_records', readonly=True, help_text="number of records matched") sort_by = ToOneField(CensusFieldResource, attribute='sort_by', help_text="field to sort results by") queryfilter_set = ToManyField('dds.api.QueryFilterResource', attribute='queryfilter_set', blank=True, null=True, full=True) export_jobs = ToManyField(ExportJobResource, attribute='exportjob_set', help_text="jobs run with this query", full=True, blank=True, null=True) class Meta: queryset = Query.objects.all() authentication = SessionAuthentication() authorization = OwnedOnlyAuthorization() def obj_create(self, bundle, **kwargs): return super(QueryResource, self).obj_create(bundle, account=bundle.request.user.account, **kwargs) def obj_get_list(self, bundle, **kwargs): return [ f for f in super(QueryResource, self).obj_get_list(bundle, **kwargs) if f.account == bundle.request.user.account ] def obj_get(self, bundle, **kwargs): result = super(QueryResource, self).obj_get(bundle, **kwargs) if result.account != bundle.request.user.account: raise Unauthorized("Forbidden") return result def apply_authorization_limits(self, request, object_list): return object_list.filter(account=request.user.account)
class BookResource(ModelResource): genres = ToManyField('api.resources.BookGenreMappingResource', 'genres', full=True) class Meta: queryset = Books.objects.all().exclude( image_url= "https://s.gr-assets.com/assets/nophoto/book/111x148-bcc042a9c91a29c1d680899eff700a03.png" ) resource_name = 'books' allowed_methods = ['get'] ordering = [ 'average_rating', 'ratings_count', 'publication_year', 'publication_month' ] filtering = { 'average_rating': ALL, 'genres': ALL_WITH_RELATIONS, 'publication_year': ALL, 'title': ALL } def get_object_list(self, request): results = super(BookResource, self).get_object_list(request) return results def dehydrate(self, bundle): return bundle
class ArtistResource(ModelResource): tags = ToManyField(TagResource, attribute=lambda bundle: Tag.objects.filter(artist=bundle.obj), blank=True) albums = ToManyField("repertoire.api.resources.AlbumResource", attribute=lambda bundle: Album.objects.filter(artist=bundle.obj), blank=True, null=True) tracks = ToManyField("repertoire.api.resources.TrackResource", attribute=lambda bundle: Track.objects.filter(artist=bundle.obj), blank=True, null=True) class Meta: queryset = Artist.objects.filter() allowed_methods = ['get', 'post', 'put', 'delete'] authentication = MultiAuthentication(BasicAuthentication(realm="Open Sound Stream: ArtistResource"), ApiKeyOnlyAuthentication()) authorization = UserObjectsOnlyAuthorization() def obj_create(self, bundle, **kwargs): return super(ArtistResource, self).obj_create(bundle, user=bundle.request.user)
class BehaviorResource(FootprintResource): parents = ToManyField('self', attribute='parents', null=False) intersection = ToOneFieldWithSubclasses( IntersectionResource, attribute='intersection_subclassed', null=True) class Meta(FootprintResource.Meta): queryset = Behavior.objects.filter(deleted=False)
class ClassResource(ModelResource): # for every Class object, tastypie will run Class.students ( or . w/e string passed in!) # If full is set to 'False' you will not see the info, about the student just # the f*****g URI students = ToManyField(StudentResource, 'students', full=True) class Meta: # make this way faster with prefetch and/or annotate # http://rocketu.yetihq.com/week9/2_pm/#/2/6 queryset = Class.objects.all() resource_name = "class" authentication = Authentication() authorization = Authorization() # tastypire takes this dict and makes it intp a filter, that would previously have to have # been written like poor people! # http://django-tastypie.readthedocs.org/en/latest/search.html?q=filtering&check_keywords=yes&area=default filtering = { 'students': ALL_WITH_RELATIONS, 'title': ['contains', 'icontains'], 'start_date': [ 'gt', ] }
class GiverfullResource(ModelResource): charities = ToManyField(CharityResource, 'charities', full=True, null=True) class Meta: queryset = Giver.objects.all() resource_name = "giver_full" authorization = Authorization() allowed_methods = ['get', 'post']
class AnalysisModuleResource(FootprintResource): config_entity = ToOneField( 'footprint.main.resources.config_entity_resources.ConfigEntityResource', attribute='config_entity', full=False, null=False, readonly=True) analysis_tools = ToManyField(AnalysisToolResource, attribute='analysis_tools') started = DateField(readonly=True) completed = DateField(readonly=True) failed = DateField(readonly=True) class Meta(FootprintResource.Meta): always_return_data = True, excludes = ('creator', 'updater') filtering = {"config_entity": ALL_WITH_RELATIONS} queryset = AnalysisModule.objects.all() resource_name = 'analysis_module' def hydrate(self, bundle): if not bundle.obj.id: bundle.obj.creator = self.resolve_user(bundle.request.GET) bundle.obj.updater = self.resolve_user(bundle.request.GET) return bundle
class PropertyResource(FlatListMixin, ModelResource): contact = ToOneField('nexus.api.ContactResource', 'contact', null=True) portfolio = ToOneField('nexus.api.PortfolioResource', 'portfolio', null=True) client = ToOneField('nexus.api.ClientResource', 'client', null=True, full=False) addresses = ToManyField('nexus.api.AddressResource', 'address_set', null=True, full_detail=True, full=True, related_name='property') class Meta: queryset = Property.objects.all() resource_name = 'property' authorization = Authorization() always_return_data = True include_absolute_url = True filtering = { 'client': ALL_WITH_RELATIONS, 'portfolio': ALL_WITH_RELATIONS }
class ReviewTeamSettingsResource(ModelResource): group = ToOneField(GroupResource, 'group') review_types = ToManyField(ReviewTypeNameResource, 'review_types', null=True) review_results = ToManyField(ReviewResultNameResource, 'review_results', null=True) class Meta: queryset = ReviewTeamSettings.objects.all() serializer = api.Serializer() cache = SimpleCache() #resource_name = 'reviewteamsettings' filtering = { "id": ALL, "autosuggest": ALL, "group": ALL_WITH_RELATIONS, "review_types": ALL_WITH_RELATIONS, "review_results": ALL_WITH_RELATIONS, }
class UploadedDataResource(ModelResource): """ API for accessing UploadedData. """ user = ForeignKey(ProfileResource, 'user') file_size = CharField(attribute='filesize', readonly=True) layers = ToManyField(UploadedLayerResource, 'uploadlayer_set', full=True) file_url = CharField(attribute='file_url', readonly=True, null=True) class Meta: queryset = UploadedData.objects.all() resource_name = 'data' allowed_methods = ['get', 'delete'] authorization = UserOwnsObjectAuthorization() authentication = SessionAuthentication() filtering = {'user': ALL_WITH_RELATIONS} def get_object_list(self, request): """ Filters the list view by the current user. """ queryset = super(UploadedDataResource, self).get_object_list(request) if not request.user.is_superuser: return queryset.filter(user=request.user) return queryset
class ClassResource(ModelResource): # ToOneField for one to one. # ToManyField for everything else. # full=False returns resource's URI instead students = ToManyField(StudentResource, 'students', full=False) class Meta: queryset = Class.objects.all() resource_name = "class" allowed_methods = ['get', 'post', 'put', 'delete'] authentication = Authentication() authorization = Authorization() always_return_data = True # Filtering allows you to look at things like this # http://127.0.0.1:8000/api/v1/class/?start_date__gt=2014-01-01&format=json filtering = { 'students': ALL_WITH_RELATIONS, 'title': ['contains', 'icontains'], 'start_date': [ 'gt', ] # Other options include: # ['exact', 'range', 'gt', 'gte', 'lt', 'lte'] }
class TimeSlotResource(ModelResource): meeting = ToOneField(MeetingResource, 'meeting') type = ToOneField(TimeSlotTypeNameResource, 'type') location = ToOneField(RoomResource, 'location', null=True) sessions = ToManyField(SessionResource, 'sessions', null=True) duration = api.TimedeltaField('duration') class Meta: cache = SimpleCache() queryset = TimeSlot.objects.all() serializer = api.Serializer() #resource_name = 'timeslot' ordering = [ 'time', 'modified', 'meeting', ] filtering = { "id": ALL, "name": ALL, "time": ALL, "duration": ALL, "show_location": ALL, "modified": ALL, "meeting": ALL_WITH_RELATIONS, "type": ALL_WITH_RELATIONS, "location": ALL_WITH_RELATIONS, "sessions": ALL_WITH_RELATIONS, }
class PolicySetResource(ModelResource): policies = ToManyField(PolicyResource, 'policies') class Meta: always_return_data = True queryset = PolicySet.objects.all() resource_name = 'policy_set'
class SessionResource(ModelResource): meeting = ToOneField(MeetingResource, 'meeting') type = ToOneField(TimeSlotTypeNameResource, 'type') group = ToOneField(GroupResource, 'group') requested_by = ToOneField(PersonResource, 'requested_by') status = ToOneField(SessionStatusNameResource, 'status') materials = ToManyField(DocumentResource, 'materials', null=True) resources = ToManyField(ResourceAssociationResource, 'resources', null=True) assignments = ToManyField( 'ietf.meeting.resources.SchedTimeSessAssignmentResource', 'timeslotassignments', null=True) requested_duration = api.TimedeltaField('requested_duration') class Meta: cache = SimpleCache() queryset = Session.objects.all() serializer = api.Serializer() #resource_name = 'session' ordering = [ 'modified', 'scheduled', 'meeting', ] filtering = { "id": ALL, "name": ALL, "short": ALL, "attendees": ALL, "agenda_note": ALL, "requested": ALL, "requested_duration": ALL, "comments": ALL, "scheduled": ALL, "modified": ALL, "meeting": ALL_WITH_RELATIONS, "type": ALL_WITH_RELATIONS, "group": ALL_WITH_RELATIONS, "requested_by": ALL_WITH_RELATIONS, "status": ALL_WITH_RELATIONS, "materials": ALL_WITH_RELATIONS, "resources": ALL_WITH_RELATIONS, "assignments": ALL_WITH_RELATIONS, }
class DocumentResource(ModelResource): type = ToOneField(DocTypeNameResource, 'type', null=True) stream = ToOneField(StreamNameResource, 'stream', null=True) group = ToOneField(GroupResource, 'group', null=True) intended_std_level = ToOneField(IntendedStdLevelNameResource, 'intended_std_level', null=True) std_level = ToOneField(StdLevelNameResource, 'std_level', null=True) ad = ToOneField(PersonResource, 'ad', null=True) shepherd = ToOneField(EmailResource, 'shepherd', null=True) states = ToManyField(StateResource, 'states', null=True) tags = ToManyField(DocTagNameResource, 'tags', null=True) rfc = CharField(attribute='rfc_number', null=True) submissions = ToManyField('ietf.submit.resources.SubmissionResource', 'submission_set', null=True) class Meta: cache = SimpleCache() queryset = Document.objects.all() serializer = api.Serializer() #resource_name = 'document' filtering = { "time": ALL, "title": ALL, "abstract": ALL, "rev": ALL, "pages": ALL, "order": ALL, "expires": ALL, "notify": ALL, "external_url": ALL, "note": ALL, "internal_comments": ALL, "name": ALL, "type": ALL_WITH_RELATIONS, "stream": ALL_WITH_RELATIONS, "group": ALL_WITH_RELATIONS, "intended_std_level": ALL_WITH_RELATIONS, "std_level": ALL_WITH_RELATIONS, "ad": ALL_WITH_RELATIONS, "shepherd": ALL_WITH_RELATIONS, "states": ALL_WITH_RELATIONS, "tags": ALL_WITH_RELATIONS, }
class ChefResource(ModelResource): chefify_user = ToOneField(ChefifyUserResource, 'chefify_user', full=True) menu = ToOneField(MenuResource, 'menu', full=True, null=True) cuisine = ToManyField(CuisineResource, 'cuisine', full=True, null=True) class Meta: queryset = Chef.objects.all() resource_name = 'chef' filtering = {'menu': ALL_WITH_RELATIONS, 'price_minimum': ALL}
class PlanResource(ModelResource): plan = ToManyField('bills.api.resources.BillResource', 'plan', full=True, null=True) class Meta: queryset = Plan.objects.all() resource_name = 'plan' authorization = Authorization() authentication = Authentication() cache = SimpleCache(timeout=1000)
class SubscriberResource(ModelResource): subscriber = ToManyField('bills.api.resources.BillResource', 'subscriber', full=True, null=True) class Meta: queryset = Subscriber.objects.all() resource_name = 'subscriber' authorization = Authorization() authentication = Authentication() cache = SimpleCache(timeout=1000)
class AppraisalResource(SpecifiedFields): engagement_property = ToOneField('nexus.api.EngagementPropertyResource', 'engagement_property', full=True) assignments = ToManyField('nexus.api.AssignmentResource', 'assignments', full=True) office = ToOneField('nexus.api.OfficeResource', 'office', full=True, null=True) class Meta: queryset = (Appraisal.objects.prefetch_related( 'assignments', 'assignments__employee').all()) resource_name = 'appraisal' authorization = Authorization() filtering = { 'engagement_property': ALL_WITH_RELATIONS, 'due_date': ALL, 'assignments': ALL_WITH_RELATIONS, 'status': ALL, 'office': ALL_WITH_RELATIONS, } always_return_data = True include_absolute_url = True excludes = [ 'created', 'changed', ] max_limit = None def dehydrate_fee(self, bundle): employee = bundle.request.user.employee if employee.title in Title.view_fee_titles: return bundle.obj.fee return None def dehydrate(self, bundle): print 'enter AppraisalResource.dehydrate' bundle = super(self.__class__, self).dehydrate(bundle) assn = bundle.obj.lead_appraiser bundle.data['lead_appraiser'] = assn.employee if assn else None bundle.data['portfolio'] = bundle.obj.engagement_property.\ engagement.portfolio.get_absolute_url() if \ bundle.obj.engagement_property.engagement.\ portfolio else None # TODO: We don't want the serialized string (.json()) here but rather # an actual dict of the address. addy = bundle.obj.engagement_property.property.base_address bundle.data['base_address'] = addy.json() if addy else None print '------- exit AppraisalResource.dehydrate' return bundle
class DocHistoryResource(ModelResource): type = ToOneField(DocTypeNameResource, 'type', null=True) stream = ToOneField(StreamNameResource, 'stream', null=True) group = ToOneField(GroupResource, 'group', null=True) intended_std_level = ToOneField(IntendedStdLevelNameResource, 'intended_std_level', null=True) std_level = ToOneField(StdLevelNameResource, 'std_level', null=True) ad = ToOneField(PersonResource, 'ad', null=True) shepherd = ToOneField(EmailResource, 'shepherd', null=True) doc = ToOneField(DocumentResource, 'doc') states = ToManyField(StateResource, 'states', null=True) tags = ToManyField(DocTagNameResource, 'tags', null=True) class Meta: cache = SimpleCache() queryset = DocHistory.objects.all() serializer = api.Serializer() #resource_name = 'dochistory' filtering = { "id": ALL, "time": ALL, "title": ALL, "abstract": ALL, "rev": ALL, "pages": ALL, "order": ALL, "expires": ALL, "notify": ALL, "external_url": ALL, "note": ALL, "internal_comments": ALL, "name": ALL, "type": ALL_WITH_RELATIONS, "stream": ALL_WITH_RELATIONS, "group": ALL_WITH_RELATIONS, "intended_std_level": ALL_WITH_RELATIONS, "std_level": ALL_WITH_RELATIONS, "ad": ALL_WITH_RELATIONS, "shepherd": ALL_WITH_RELATIONS, "doc": ALL_WITH_RELATIONS, "states": ALL_WITH_RELATIONS, "tags": ALL_WITH_RELATIONS, }
def test_hydrate(self): note = Note.objects.get(pk=1) bundle = Bundle(obj=note) # With no value or nullable, we should get an ``ApiFieldError``. field_1 = ToManyField(SubjectResource, 'subjects') field_1.instance_name = 'm2m' self.assertRaises(ApiFieldError, field_1.hydrate_m2m, bundle) # The nullable case. field_2 = ToManyField(SubjectResource, 'subjects', null=True) field_2.instance_name = 'm2m' empty_bundle = Bundle() self.assertEqual(field_2.hydrate_m2m(empty_bundle), []) field_3 = ToManyField(SubjectResource, 'subjects', null=True) field_3.instance_name = 'm2m' bundle_3 = Bundle(data={'m2m': []}) self.assertEqual(field_3.hydrate_m2m(bundle_3), []) # Wrong resource URI. field_4 = ToManyField(SubjectResource, 'subjects') field_4.instance_name = 'm2m' bundle_4 = Bundle(data={'m2m': ['/api/v1/subjects/abc/']}) self.assertRaises(NotFound, field_4.hydrate_m2m, bundle_4) # A real, live attribute! field_5 = ToManyField(SubjectResource, 'subjects') field_5.instance_name = 'm2m' bundle_5 = Bundle(data={'m2m': ['/api/v1/subjects/1/']}) subject_bundle_list = field_5.hydrate_m2m(bundle_5) self.assertEqual(len(subject_bundle_list), 1) self.assertEqual(subject_bundle_list[0].data['name'], u'News') self.assertEqual(subject_bundle_list[0].data['url'], u'/news/') self.assertEqual(subject_bundle_list[0].obj.name, u'News') self.assertEqual(subject_bundle_list[0].obj.url, u'/news/') field_6 = ToManyField(SubjectResource, 'subjects') field_6.instance_name = 'm2m' bundle_6 = Bundle(data={'m2m': [ { 'name': u'Foo', 'url': u'/foo/', }, { 'name': u'Bar', 'url': u'/bar/', }, ]}) subject_bundle_list = field_6.hydrate_m2m(bundle_6) self.assertEqual(len(subject_bundle_list), 2) self.assertEqual(subject_bundle_list[0].data['name'], u'Foo') self.assertEqual(subject_bundle_list[0].data['url'], u'/foo/') self.assertEqual(subject_bundle_list[0].obj.name, u'Foo') self.assertEqual(subject_bundle_list[0].obj.url, u'/foo/') self.assertEqual(subject_bundle_list[1].data['name'], u'Bar') self.assertEqual(subject_bundle_list[1].data['url'], u'/bar/') self.assertEqual(subject_bundle_list[1].obj.name, u'Bar') self.assertEqual(subject_bundle_list[1].obj.url, u'/bar/') # The blank case. field_7 = ToManyField(SubjectResource, 'fk', blank=True) field_7.instance_name = 'fk' self.assertEqual(field_7.hydrate(bundle_6), None) field_8 = ToManyField(SubjectResource, 'm2m', blank=True) field_8.instance_name = 'm2m' subject_bundle_list_2 = field_8.hydrate_m2m(bundle_6) self.assertEqual(len(subject_bundle_list_2), 2) self.assertEqual(subject_bundle_list_2[0].data['name'], u'Foo') self.assertEqual(subject_bundle_list_2[0].data['url'], u'/foo/') self.assertEqual(subject_bundle_list_2[0].obj.name, u'Foo') self.assertEqual(subject_bundle_list_2[0].obj.url, u'/foo/') self.assertEqual(subject_bundle_list_2[1].data['name'], u'Bar') self.assertEqual(subject_bundle_list_2[1].data['url'], u'/bar/') self.assertEqual(subject_bundle_list_2[1].obj.name, u'Bar') self.assertEqual(subject_bundle_list_2[1].obj.url, u'/bar/') # The readonly case. field_9 = ToManyField(SubjectResource, 'subjects', readonly=True) field_9.instance_name = 'm2m' self.assertEqual(field_9.hydrate(bundle_6), None) # A related object. field_10 = ToManyField(MediaBitResource, 'media_bits', related_name='note') field_10.instance_name = 'mbs' note_1 = Note.objects.get(pk=1) bundle_10 = Bundle(obj=note_1, data={'mbs': [ { 'title': 'Foo!', }, ]}) media_bundle_list = field_10.hydrate_m2m(bundle_10) self.assertEqual(len(media_bundle_list), 1) self.assertEqual(media_bundle_list[0].obj.title, u'Foo!')
def test_has_default(self): field_1 = ToManyField(SubjectResource, 'subjects') self.assertEqual(field_1.has_default(), False) field_2 = ToManyField(SubjectResource, 'subjects', default=1) self.assertEqual(field_2.has_default(), True)
def test_dehydrate(self): note = Note() bundle_1 = Bundle(obj=note) field_1 = ToManyField(SubjectResource, 'subjects') field_1.instance_name = 'm2m' self.assertRaises(ApiFieldError, field_1.dehydrate, bundle_1) field_2 = ToManyField(SubjectResource, 'subjects', null=True) field_2.instance_name = 'm2m' self.assertEqual(field_2.dehydrate(bundle_1), []) field_3 = ToManyField(SubjectResource, 'subjects') field_3.instance_name = 'm2m' bundle_3 = Bundle(obj=self.note_1) self.assertEqual(field_3.dehydrate(bundle_3), ['/api/v1/subjects/1/', '/api/v1/subjects/2/']) field_4 = ToManyField(SubjectResource, 'subjects', full=True) field_4.instance_name = 'm2m' bundle_4 = Bundle(obj=self.note_1) subject_bundle_list = field_4.dehydrate(bundle_4) self.assertEqual(len(subject_bundle_list), 2) self.assertEqual(isinstance(subject_bundle_list[0], Bundle), True) self.assertEqual(subject_bundle_list[0].data['name'], u'News') self.assertEqual(subject_bundle_list[0].data['url'], u'/news/') self.assertEqual(subject_bundle_list[0].obj.name, u'News') self.assertEqual(subject_bundle_list[0].obj.url, u'/news/') self.assertEqual(isinstance(subject_bundle_list[1], Bundle), True) self.assertEqual(subject_bundle_list[1].data['name'], u'Photos') self.assertEqual(subject_bundle_list[1].data['url'], u'/photos/') self.assertEqual(subject_bundle_list[1].obj.name, u'Photos') self.assertEqual(subject_bundle_list[1].obj.url, u'/photos/') field_5 = ToManyField(SubjectResource, 'subjects') field_5.instance_name = 'm2m' bundle_5 = Bundle(obj=self.note_2) self.assertEqual(field_5.dehydrate(bundle_5), ['/api/v1/subjects/1/', '/api/v1/subjects/3/']) field_6 = ToManyField(SubjectResource, 'subjects') field_6.instance_name = 'm2m' bundle_6 = Bundle(obj=self.note_3) self.assertEqual(field_6.dehydrate(bundle_6), []) try: # Regression for missing variable initialization. field_7 = ToManyField(SubjectResource, None) field_7.instance_name = 'm2m' bundle_7 = Bundle(obj=self.note_3) field_7.dehydrate(bundle_7) self.fail('ToManyField requires an attribute of some type.') except ApiFieldError: pass