class DealershipReadSerializer(serializers.ModelSerializer): """A Read serializer for the Dealership table""" general_manager = PersonSerializer() sales_reps = PersonSerializer(many=True) class Meta: model = Dealership fields = [ 'id', 'name', 'max_fleet_count', 'is_active', 'general_manager', 'sales_reps' ]
class ThoughtSerializer(serializers.HyperlinkedModelSerializer): serializer_url_field = partial( serializers.HyperlinkedIdentityField, lookup_field="slug", lookup_url_kwarg="slug", ) authors = PersonSerializer(many=True) attachments = AttachmentSerializer(many=True) class Meta: model = Thought fields = [ "id", "url", "slug", "title", "description", "image_url", "image_description", "thought_html", "date", "authors", "attachments", ]
def list(self, request): doctors = Person.objects.filter(title="Dr.") results = { "doctors": PersonSerializer(doctors, many=True).data, } return Response(results)
class JustSermonSerializer(serializers.HyperlinkedModelSerializer): serializer_url_field = partial( serializers.HyperlinkedIdentityField, lookup_field="slug", lookup_url_kwarg="slug", ) speakers = PersonSerializer(many=True) soundcloud_assets = SoundCloudAssetSerializer(many=True) youtube_assets = YouTubeAssetSerializer(many=True) attachments = AttachmentSerializer(many=True) class Meta: model = Sermon fields = [ "id", "url", "slug", "title", "description", "date", "speakers", "soundcloud_assets", "youtube_assets", "attachments", ]
def get_context_data(self, **kwargs): context = super(ProfileDetail, self).get_context_data(**kwargs) person = get_or_create_person(self.request) serializer = PersonSerializer(person) context['person'] = person context['serializer'] = serializer context['demographic_form'] = DemographicForm( instance=person.demographic) email = None username = None if person.user: if person.user.email: email = person.user.email username = person.user.username else: if person.profile_email: email = person.profile_email else: email = '' if person.username: username = person.username else: username = '' context['person_form'] = PersonForm(instance=person, initial={ 'email': email, 'username': username }) context['groups_form'] = GroupsForm(instance=person, request=self.request) known_languages = KnownLanguage.objects.filter(person=person).count() if known_languages > 0: extra = known_languages else: extra = 1 KnownLanguageFormset = inlineformset_factory( Person, KnownLanguage, form=KnownLanguageFormWithPerson, fields=('language', 'level_of_proficiency', 'person', 'accent', 'dialect'), max_num=get_num_supported_languages(), extra=extra) kl_formset = KnownLanguageFormset(instance=person, form_kwargs={'person': person}) context['known_language_form'] = kl_formset context['known_languages'] = known_languages context['show_stats'] = True return context
def test_get_valid_single_person(self): response = client.get(f"/api/people/{self.jane.pk}/") # print(response.data) # print(response.status_code) person = Person.objects.get(pk=self.jane.pk) serializer = PersonSerializer(person) self.assertEqual(response.data, serializer.data) self.assertEqual(response.status_code, status.HTTP_200_OK)
class ServiceRequestSerializer(serializers.ModelSerializer): owner_object = PersonSerializer(source='owner', required=False, read_only=True) reporter_object = PersonSerializer(source='reporter', required=False, read_only=True) full_address = serializers.SerializerMethodField() animals = AnimalSerializer(source='animal_set', many=True, required=False, read_only=True) aco_required = serializers.SerializerMethodField() animal_count = serializers.IntegerField(read_only=True) injured = serializers.BooleanField(read_only=True) # Custom field for the full address. def get_full_address(self, obj): return build_full_address(obj) # Custom field for if any animal is ACO Required. If it is aggressive or "Other" species. def get_aco_required(self, obj): return obj.animal_set.filter(Q(aggressive='yes') | Q(species='other')).exists() # Updates datetime fields to null when receiving an empty string submission. # Truncates latitude and longitude. def to_internal_value(self, data): if data.get('recovery_time') == '': data['recovery_time'] = None if data.get('owner_notification_tstamp') == '': data['owner_notification_tstamp'] = None if data.get('latitude'): data['latitude'] = float("%.6f" % float(data.get('latitude'))) if data.get('longitude'): data['longitude'] = float("%.6f" % float(data.get('longitude'))) return super().to_internal_value(data) class Meta: model = ServiceRequest fields = '__all__'
def test_get_all_people(self): # get API response response = client.get('/api/people/') # print(response.data) # print(response.status_code) # get data from db people = Person.objects.all() serializer = PersonSerializer(people, many=True) # print(serializer.data) self.assertEqual(response.data, serializer.data) self.assertEqual(response.status_code, status.HTTP_200_OK)
def listing(request): doctors = Person.objects.filter(title='Dr.') vehicles = Vehicle.objects.all() context = { 'request': request, } vehicles_serializer = VehicleSerializer(vehicles, many=True, context=context) results = { 'doctors': PersonSerializer(doctors, many=True).data, 'vehicles': vehicles_serializer.data, } return Response(results)
def listing(request): doctors = Person.objects.filter(title="Dr.") vehicles = Vehicle.objects.all() context = { "request": request, } vehicle_serializer = VehicleSerializer(vehicles, many=True, context=context) results = { "doctors": PersonSerializer(doctors, many=True).data, "vehicles": vehicle_serializer.data, } return Response(results)
def people_list(request): if request.method == 'GET': if len(request.query_params) == 0: people = Person.objects.all() serializer = PersonSerializer(people, many=True) return Response(serializer.data, status=status.HTTP_200_OK) name = request.query_params.get("name") if name is None: return Response({"error": "no name in query params"}, status=status.HTTP_400_BAD_REQUEST) else: people = Person.objects.filter(name=name) if len(people) == 0: return Response(status=status.HTTP_404_NOT_FOUND) else: serializer = PersonSerializer(people, many=True) return Response(serializer.data, status=status.HTTP_200_OK) elif request.method == 'POST': data = request.data serializer = PersonSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class AnimalSerializer(serializers.ModelSerializer): owner_object = PersonSerializer(source='owner', required=False, read_only=True) full_address = serializers.SerializerMethodField() aco_required = serializers.SerializerMethodField() front_image = serializers.SerializerMethodField() side_image = serializers.SerializerMethodField() extra_images = serializers.SerializerMethodField() shelter_name = serializers.SerializerMethodField() shelter = serializers.SerializerMethodField() def get_shelter(self, obj): if obj.room: return obj.room.building.shelter.id return None # Custom field for the full address. def get_full_address(self, obj): # Use the Room address first if it exists. if obj.room: return build_full_address(obj.room.building.shelter) # Then use the SR address if it exists. elif obj.request: return build_full_address(obj.request) # Otherwise use the owner address. return build_full_address(obj.owner) def get_shelter_name(self, obj): if obj.room: return obj.room.building.shelter.name return '' # An Animal is ACO Required if it is aggressive or "Other" species. def get_aco_required(self, obj): return (obj.aggressive or obj.species.other) def get_front_image(self, obj): try: return AnimalImage.objects.get(animal=obj, category="front_image").image.url except ObjectDoesNotExist: return '' def get_side_image(self, obj): try: return AnimalImage.objects.get(animal=obj, category="side_image").image.url except ObjectDoesNotExist: return '' def get_extra_images(self, obj): return [ animal_image.image.url for animal_image in AnimalImage.objects.filter(animal=obj, category="extra") ] class Meta: model = Animal fields = '__all__'
def post(self, request, format=None): serializer = PersonSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request, format=None): people = Person.objects.all() serializer = PersonSerializer(people, many=True) return Response(serializer.data)
def test_serializer(self): """ Test serialization is correct (and should test deserialization, etc) """ ps = PersonSerializer(self.person_one) self.assertEqual(ps.data['name'], "William")
def send_person(self, event): person = Person.objects.get(id=event['id']) p = PersonSerializer(person).data self.send_json({ "person": p })
def then_response_body_should_be_that_person_serialized(self): assert self.body == PersonSerializer.serialize(self.person) return self