【发布时间】:2018-05-19 05:27:33
【问题描述】:
我正在使用Django 2.0 和Django REST Framework。
我在联系人应用程序中有两个模型
contacts/models.py
class Contact(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100, blank=True, null=True, default='')
class ContactPhoneNumber(models.Model):
contact = models.ForeignKey(Contact, on_delete=models.CASCADE)
phone = models.CharField(max_length=100)
primary = models.BooleanField(default=False)
def __str__(self):
return self.phone
contacts/serializers.py
class ContactPhoneNumberSerializer(serializers.ModelSerializer):
class Meta:
model = ContactPhoneNumber
fields = ('id', 'phone', 'primary', 'created', 'modified')
和contacts/views.py
class ContactPhoneNumberViewSet(viewsets.ModelViewSet):
serializer_class = ContactPhoneNumberSerializer
def get_queryset(self):
return ContactPhoneNumber.objects.filter(
contact__user=self.request.user
)
urls.py
router.register(r'contact-phone', ContactPhoneNumberViewSet, 'contact_phone_numbers')
我想要的是跟随端点
-
GET:
/contact-phone/{contact_id}/列出特定联系人的电话号码 -
POST:
/contact-phone/{contact_id}/将电话号码添加到特定联系人 -
PUT:
/contact-phone/{contact_phone_number_id}/更新特定电话号码 -
删除:
/contact-phone/{contact_phone_number_id}/删除特定电话号码
PUT 和Delete 可以作为ModelViewSet 的默认操作实现,但是如何使get_queryset 接受contact_id 作为必需参数?
编辑 2
我关注了文档Binding ViewSets to URLs explicitly
更新app/urls.py
router = routers.DefaultRouter()
router.register(r'contacts', ContactViewSet, 'contacts')
contact_phone_number_view_set = ContactPhoneNumberViewSet.as_view({
'get': 'list/<contact_pk>/',
'post': 'create/<contact_pk>/',
'put': 'update',
'delete': 'destroy'
})
router.register(r'contact-phone-number', contact_phone_number_view_set, 'contact_phone_numbers')
urlpatterns = [
path('api/', include(router.urls)),
url(r'^admin/', admin.site.urls),
]
但是报错了
AttributeError: 'function' object has no attribute 'get_extra_actions'
【问题讨论】:
标签: django django-rest-framework