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