Django Rest Framework将相关模型与当前用户相关联

时间:2014-07-25 17:47:35

标签: django django-rest-framework

我首先解释一下我的问题的当前情况。

模型

例如,有5个模型:CommunityUserMembershipReservationItem

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是m:m UserMembership
  •   
  • Reservation为1:m Membership
  •   
  • Item为1:m Reservation
  •   

ModelSerializer

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

问题

User自动设置request.user值的最佳方法是什么,因此ReservationSerializer所需的属性只是communityitem代替membershipitem

参考

1 个答案:

答案 0 :(得分:0)

序列化程序的作用是以清晰的方式表示信息,而不是操纵此类数据。您可能希望在视图上执行此操作:使用DRF上可用的通用ListCreateAPIView,您可以使用pre_save信号来存储该信息:

from rest_framework.generics import ListCreateAPIView

class ReservationView(ListCreateAPIView):
    def pre_save(self, obj):
        obj.membership.user = self.request.user