简体   繁体   中英

Sending patch request to Django Rest Framework API with Foreign Key

I need to send put request to API for which I know only the foreign key. How am supposed to do this.

models.py

class Company(models.Model):
    name = models.CharField(max_length = 100)
    user = models.OneToOneField(settings.AUTH_USER_MODEL, unique = True)

serializer.py

class CompanySerializer(serializers.ModelSerializer):

   class Meta:
       model = Company
       fields = ('id', 'name','user')

views.py

class Company(object):
    permission_classes = (IsAuthenticated,IsUserThenReadPatch)
    serializer_class = CompanySerializer

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

class CompanyDetails(Company, RetrieveUpdateAPIView, APIView):

    pass

urls.py

url(r'^company/$',views.CompanyDetails.as_view()),

In order to enable all CRUD operations in DRF you probably want to use ViewSet instead of View :

# views.py
class CompanyViewSet(ViewSet):
    permission_classes = (IsAuthenticated,IsUserThenReadPatch)
    serializer_class = CompanySerializer

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

# urls.py
router = routers.SimpleRouter()
router.register(r'company', CompanyViewSet)
urlpatterns = router.urls

The above will allow you do send all CRUD REST requests:

  • GET /company - list all companies
  • POST /company - create a company
  • GET /company/:id - get a single company
  • PUT/POST /company/:id - update a company
  • PATCH /company/:id - partially update a company
  • DELETE /company/:id - delete a company

You can read more in the DRF docs - viewsets and routers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM