Django Rest Framework associating Related Model with current User

I'll start by explaining the current scenario of my problem.

Models

There are 5 models for example: Community , User , Membership , Reservation , Item

class User(Model):
    name = CharField(max_length=50)
    communities = ManyToManyField('Community', through='Membership')


class Community(Model):
    name = CharField(max_length=50)


class Membership(Model):
    user = ForeignKey('User')
    community = ForeignKey('Community')


class Item(Model):
    name = CharField(max_length=50)


class Reservation(Model):
    item = ForeignKey('Item')
    membership = ForeignKey('Membership')
  • Community is m:m User through Membership .
  • Reservation is 1:m Membership
  • Item is 1:m Reservation
  • ModelSerializer

    class ReservationSerializer(ModelSerializer):
        class Meta:
            model = Reservation
            fields = ('membership', 'item')
    

    Problem

    What's the best approach to automatically set the User value from request.user , hence the attribute that is required for this ReservationSerializer is just the community and item instead of membership and item ?

    References

  • How to create a django User using DRF's ModelSerializer
  • Return the current user with Django Rest Framework
  • http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions#associating-snippets-with-users
  • Django Rest Framework ModelSerializer Set attribute on create
  • Dynamically limiting queryset of related field
  • djangorestframework: Filtering in a related field

  • The role of the serializer is to represent the information in a legible way, not to manipulate such data. You may want to do that on a view: Using the generic ListCreateAPIView available on DRF, you could use the pre_save signal to store that information:

    from rest_framework.generics import ListCreateAPIView
    
    class ReservationView(ListCreateAPIView):
        def pre_save(self, obj):
            obj.membership.user = self.request.user
    
    链接地址: http://www.djcxy.com/p/95208.html

    上一篇: 由于从boss线程传递给工作线程的请求的netty延迟?

    下一篇: Django Rest Framework将相关模型与当前用户相关联