1

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

Community
  • 1
  • 1
Yeo
  • 11,416
  • 6
  • 63
  • 90
  • I am trying to leverage the ModelSerializer, as much as I could, so that I can avoid writing custom serializer from scratch. – Yeo Jul 25 '14 at 17:49

1 Answers1

0

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
fixmycode
  • 8,220
  • 2
  • 28
  • 43
  • The issues is that the client has to make a GET request on the Membership resource, just to get the `membership_id` before able to POST to the `Reservation` resource, which I think an extra step that is not necessarily to be done on every client. They should be able to do POST with their current `community_id`, without having to know what is the membership_id for my own account in this community. – Yeo Jul 25 '14 at 18:37
  • in DRF 3.x this was renamed to perform_create() http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/#associating-snippets-with-users – Eduard Gamonal Nov 09 '15 at 11:27