drf

이승연·2021년 10월 11일
0

업무일지들

목록 보기
41/49
>>> Session.__dict__.keys()
dict_keys(['__module__', 'SessionStatus', 'return_session_round', '__doc__', '_meta', 'DoesNotExist', 'MultipleObjectsReturned', 'session_batch_id', 'session_batch', 'scheduled_datetime', 'get_next_by_scheduled_datetime', 'get_previous_by_scheduled_datetime', 'counselor_id', 'counselor', 'session_notice_status', 'status', 'get_status_display', 'schedule_altered', 'schedule_alter_reason', 'memo', 'get_next_by_created_at', 'get_previous_by_created_at', 'id'])

Notice that we're no longer explicitly tying our requests or responses to a given content type. request.data can handle incoming json requests, but it can also handle other formats. Similarly we're returning response objects with data, but allowing REST framework to render the response into the correct content type for us.

Hyperlinking our API
Dealing with relationships between entities is one of the more challenging aspects of Web API design. There are a number of different ways that we might choose to represent a relationship:

  • Using primary keys.
  • Using hyperlinking between entities.
  • Using a unique identifying slug field on the related entity.
  • Using the default string representation of the related entity.
  • Nesting the related entity inside the parent representation.
  • Some other custom representation.

The HyperlinkedModelSerializer has the following differences from ModelSerializer:

It does not include the id field by default.
It includes a url field, using HyperlinkedIdentityField.
Relationships use HyperlinkedRelatedField, instead of PrimaryKeyRelatedField.

viewset을 사용하면 이렇게 생긴걸:

class UserList(generics.ListAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer


class UserDetail(generics.RetrieveAPIView):
    queryset = User.objects.all()
    serializer_class = UserSerializer

이렇게 만들 수 있음:

class UserViewSet(viewsets.ReadOnlyModelViewSet):
    """
    This viewset automatically provides 'list' and 'retrieve' actions
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer

Notice that we've also used the @action decorator to create a custom action, named highlight. This decorator can be used to add any custom endpoints that don't fit into the standard create/update/delete style.

Custom actions which use the @action decorator will respond to GET requests by default. We can use the methods argument if we wanted an action that responded to POST requests.

Got AttributeError when attempting to get a value
for field product_ratings
on serializer ProductSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the Product
instance.
Original exception text was: 'Product'
object has no attribute 'product_ratings'.

이거는 리스트 형태에서 standby_days를 불ㄹ러오려고 하니 생김. onetoonefield로 바꿈

바디에 pk만 넣어서 보내도 객체를 찾아준다 <3

class UpdateMatchingSerializer(ReadMatchingSerializer):

def update(self, matching, validated_data):
    for key, value in self.initial_data.items():
        print(key, value)
        if key in ["standby_days", "memo"]:
            setattr(matching, key, value)
            matching.save()
        if key == "matching_status":
            matching.status = value
            matching.save()
        else:
            setattr(matching.application, key, value)
            matching.application.save()
    return matching

0개의 댓글