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:mUser
throughMembership
.Reservation
is 1:mMembership
Item
is 1:mReservation
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