3
我想爲我的應用程序創建一個REST API。如何使用perform_create在Django Rest Framework中自動設置字段?
urls.py在應用程序目錄看起來是這樣的:
urlpatterns = [
url(
r'^professors/(?P<pk>[0-9]+)/reviews/$',
views.ProfessorReviewList.as_view(),
name = 'user-review-list',
)
]
serializers.py
class ProfessorSerializer(serializers.HyperlinkedModelSerializer):
reviews = serializers.HyperlinkedIdentityField(view_name='professor-review-list')
class Meta:
model = Professor
fields = (
'url', 'name', 'name_code', 'university',
'department', 'total_rating_points',
'number_of_reviews', 'rating', 'reviews',
)
class ReviewSerializer(serializers.HyperlinkedModelSerializer):
author = serializers.ReadOnlyField(source='author.username')
class Meta:
model = Review
fields = (
'url', 'author', 'professor',
'created', 'updated', 'rating', 'text'
)
最後,我views.py看起來是這樣的:
class ProfessorReviewList(generics.ListCreateAPIView):
queryset = Review.objects.all()
serializer_class = ReviewSerializer
def get_queryset(self):
queryset = super(ProfessorReviewList, self).get_queryset()
return queryset.filter(professor__pk=self.kwargs.get('pk'))
permission_classes = (permissions.IsAuthenticatedOrReadOnly,
IsAuthorOrReadOnly,)
def perform_create(self, serializer):
# The request user is set as author automatically.
serializer.save(author=self.request.user)
我想要做的是當我訪問該URL時,獲得一位特定教授的所有評論的列表。如果他們願意,我也希望允許用戶在這個終點添加新的評論。一切都很好,但我想要一個系統,用戶在創建評論時不必選擇教授。
假設我去/professor/1/reviews/,獲得pk = 1的教授的所有評論的列表。現在,如果用戶添加新評論,教授將自動設置爲pk = 1的教授。用戶不會選擇。在/教授/ 2 /評論/,審查的教授領域自動設置爲教授與pk = 2等,等等。
我該怎麼做?謝謝你的幫助。
是的,但我們需要處理錯誤'pk' DoesNotExist) –