gpt4 book ai didi

django - 在 Django REST Framework 中向 get_queryset 请求添加参数

转载 作者:行者123 更新时间:2023-12-05 05:16:30 25 4
gpt4 key购买 nike

我正在使用 Django 2.0Django 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}/ 删除特定电话号码

PUTDelete 可以作为 ModelViewSet 的默认操作来实现,但是如何制作 get_queryset接受 contact_id 作为必需参数?

Edit 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'

最佳答案

您可以使用 @action 向 View 集添加额外的操作装饰者:

class ContactPhoneNumberViewSet(viewsets.ModelViewSet):
serializer_class = ContactPhoneNumberSerializer

def get_queryset(self):
return ContactPhoneNumber.objects.filter(
contact__user=self.request.user
)

@action(methods=['post'], detail=False)
def add_to_contact(self, request, contact_id=None):
contact = Contact.objects.get(id=contact_id)
serializer = ContactPhoneNumberSerializer(data=request.data)
if serializer.is_valid():
serializer.save(contact=contact)
return Response(serializer.data)
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)

@action(methods=['get'], detail=False)
def set_password(self, request, contact_id=None):
contact = Contact.objects.get(id=contact_id)
serializer = PasswordSerializer(contact.contactphonenumber_set.all(), many=True)
return Response(serializer.data)

UPD

由于您不需要额外的操作,您可以覆盖retrievecreate 默认方法:

class ContactPhoneNumberViewSet(viewsets.ModelViewSet):
serializer_class = ContactPhoneNumberSerializer

def get_queryset(self):
return ContactPhoneNumber.objects.filter(
contact__user=self.request.user
)

def create(self, request, pk=None):
contact = Contact.objects.get(id=contact_id)
serializer = ContactPhoneNumberSerializer(data=request.data)
if serializer.is_valid():
serializer.save(contact=contact)
return Response(serializer.data)
else:
return Response(serializer.errors,
status=status.HTTP_400_BAD_REQUEST)

def retrieve(self, request, pk=None):
contact = Contact.objects.get(pk=pk)
serializer = PasswordSerializer(contact.contactphonenumber_set.all(), many=True)
return Response(serializer.data)

要更改标准 create url,请使用显式 url 绑定(bind):

contact_list = ContactPhoneNumberViewSet.as_view({
'get': 'list',
'post': 'create',
'put': 'update',
'delete': 'destroy'
})

urlpatterns = [
path('api//contact-phone/<int:pk>/', contact_list, name='contact-list'),
url(r'^admin/', admin.site.urls),
]

关于django - 在 Django REST Framework 中向 get_queryset 请求添加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50422091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com