コード例 #1
0
ファイル: serializers.py プロジェクト: mitchellst/cheeky-teak
	def create(self, validated_data):
		guests = [EventGuest(**item) for item in validated_data]
		self.validate_same_invitation(guests)
		inviteNumber = EventGuest.nextFreeInvitation(guests[0].event if len(guests) > 0 else None)
		for guest in guests:
			guest.invitation = inviteNumber
		return EventGuest.objects.bulk_create(guests)
コード例 #2
0
 def create(self, validated_data):
     guests = [EventGuest(**item) for item in validated_data]
     self.validate_same_invitation(guests)
     inviteNumber = EventGuest.nextFreeInvitation(
         guests[0].event if len(guests) > 0 else None)
     for guest in guests:
         guest.invitation = inviteNumber
     return EventGuest.objects.bulk_create(guests)
コード例 #3
0
ファイル: test_models.py プロジェクト: mitchellst/cheeky-teak
	def test_nextFreeInvite_incriments(self):
		ev = Event(name='Test Event', event_date=datetime.date.today())
		ev.save()
		defaults = {'event': ev, 'first': 'FirstName', 'last': 'Last Name'}
		latest = 0
		for x in range(10):
			guest = EventGuest(invitation=EventGuest.nextFreeInvitation(ev), **defaults)
			guest.save()
			self.assertTrue(guest.invitation > latest)
			latest = guest.invitation
コード例 #4
0
ファイル: test_models.py プロジェクト: mitchellst/cheeky-teak
 def test_nextFreeInvite_incriments(self):
     ev = Event(name='Test Event', event_date=datetime.date.today())
     ev.save()
     defaults = {'event': ev, 'first': 'FirstName', 'last': 'Last Name'}
     latest = 0
     for x in range(10):
         guest = EventGuest(invitation=EventGuest.nextFreeInvitation(ev),
                            **defaults)
         guest.save()
         self.assertTrue(guest.invitation > latest)
         latest = guest.invitation
コード例 #5
0
    def many_init(cls, *args, **kwargs):
        """
		Here's where we'll validate that all the invitations are the same,
		or assign them.
		
		When passing many=True with a data kwarg, we need to make sure the representations
		are not orphaned from their event. Representations must either each have a dict key
		"event" which corresponds to the integer primary key, or you must pass the event as
		a keyword argument to the serializer along with many=True.
		
		"""
        if 'data' in kwargs:

            #validate data is a list.
            data = kwargs.pop('data')
            assert type(data) == list, (
                '''Invitation Serializer with many=True and non-empty data
				expects a list in the data representation, not a dict or other
				type.''')
            eventNumber = kwargs.pop('event', None)
            if eventNumber is None:
                try:
                    eventNumber = data[0]['event']
                except KeyError:
                    raise NoEventError(
                        '''No event information associated with this list of guests.
						Try passing `event` keyword arg to the serializer or guest representations
						with event attributes''')

            #build invitations list to analyze
            invitations = [obj.pop('invitation', None) for obj in data]
            for inx, val in enumerate(invitations):
                if type(val) == str:  #some data cleaning for types.
                    val = val.strip()
                    if val == '':
                        invitations[inx] = None
                    else:
                        try:
                            intval = int(val)
                            invitations[inx] = intval
                        except ValueError:
                            pass

            integerInvitations = [x for x in invitations if type(x) == int]

            if integerInvitations:  #isn't epmty
                allsame = map(lambda x: x == integerInvitations[0],
                              integerInvitations)
                if not all(allsame):
                    raise MixedInvitationError(
                        'All Numbered invitations must be same.')
                numberToAssign = integerInvitations[0]

            else:  #usually means invitations == [None,]*len(data):
                numberToAssign = EventGuest.nextFreeInvitation(eventNumber)
            for representation in data:
                representation['invitation'] = numberToAssign

            # put our work back in the keyword args dict, which we'll use below.
            kwargs['data'] = data

        else:
            instance_queryset = [
                args[0],
            ] if isinstance(args[0],
                            EventGuest) else args[0]  #per the serializer API.
            allsame = map(
                lambda x: x.invitation == instance_queryset[0].invitation,
                instance_queryset)
            if not all(allsame):
                raise MixedInvitationError

        # finally make the serializer, knowing the above is done.
        child = cls(*args, **kwargs)
        list_kwargs = {
            'child': child,
        }
        list_kwargs.update({
            key: value
            for key, value in kwargs.items()
            if key in serializers.LIST_SERIALIZER_KWARGS
        })
        return InvitationListSerializer(*args, **list_kwargs)
コード例 #6
0
ファイル: test_models.py プロジェクト: mitchellst/cheeky-teak
	def test_nextFreeInvitation_method_raises_exception_on_noEvent(self):
		with self.assertRaises(NoEventError):
			EventGuest.nextFreeInvitation(None)
コード例 #7
0
ファイル: serializers.py プロジェクト: mitchellst/cheeky-teak
	def many_init(cls, *args, **kwargs):
		"""
		Here's where we'll validate that all the invitations are the same,
		or assign them.
		
		When passing many=True with a data kwarg, we need to make sure the representations
		are not orphaned from their event. Representations must either each have a dict key
		"event" which corresponds to the integer primary key, or you must pass the event as
		a keyword argument to the serializer along with many=True.
		
		"""
		if 'data' in kwargs:
			
			#validate data is a list.
			data = kwargs.pop('data')
			assert type(data) == list, (
				'''Invitation Serializer with many=True and non-empty data
				expects a list in the data representation, not a dict or other
				type.'''
			)
			eventNumber = kwargs.pop('event', None)
			if eventNumber is None:
				try:
					eventNumber = data[0]['event']
				except KeyError:
					raise NoEventError(
						'''No event information associated with this list of guests.
						Try passing `event` keyword arg to the serializer or guest representations
						with event attributes'''
						)
			
			#build invitations list to analyze
			invitations = [obj.pop('invitation', None) for obj in data]
			for inx, val in enumerate(invitations):
				if type(val) == str: #some data cleaning for types.
					val = val.strip()
					if val == '':
						invitations[inx] = None
					else:
						try:
							intval = int(val)
							invitations[inx] = intval
						except ValueError:
							pass
					
			integerInvitations = [x for x in invitations if type(x)==int]
			
			if integerInvitations: #isn't epmty
				allsame = map(lambda x: x==integerInvitations[0], integerInvitations)
				if not all(allsame): 
					raise MixedInvitationError('All Numbered invitations must be same.')
				numberToAssign = integerInvitations[0]
			
			else: #usually means invitations == [None,]*len(data):
				numberToAssign = EventGuest.nextFreeInvitation(eventNumber)
			for representation in data:
				representation['invitation'] = numberToAssign
			
			# put our work back in the keyword args dict, which we'll use below.
			kwargs['data'] = data
			
		else:
			instance_queryset = [args[0],] if isinstance(args[0], EventGuest) else args[0] #per the serializer API.
			allsame = map(lambda x: x.invitation==instance_queryset[0].invitation, instance_queryset)
			if not all(allsame):
				raise MixedInvitationError
			
		# finally make the serializer, knowing the above is done.
		child = cls(*args, **kwargs)
		list_kwargs = {'child': child,}
		list_kwargs.update({
			key: value for key, value in kwargs.items()
			if key in serializers.LIST_SERIALIZER_KWARGS
		})
		return InvitationListSerializer(*args, **list_kwargs)
コード例 #8
0
ファイル: test_models.py プロジェクト: mitchellst/cheeky-teak
 def test_nextFreeInvitation_method_raises_exception_on_noEvent(self):
     with self.assertRaises(NoEventError):
         EventGuest.nextFreeInvitation(None)