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 User通过Membership
  • Reservation是1:m Membership
  • Item是1:m Reservation
  • ModelSerializer

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

    问题

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

    参考

  • 如何使用DRF的ModelSerializer创建一个django用户
  • 用Django Rest Framework返回当前用户
  • http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions#associating-snippets-with-users
  • Django Rest框架ModelSerializer在create上设置属性
  • 动态限制相关字段的查询集
  • djangorestframework:在相关字段中过滤

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

    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/95207.html

    上一篇: Django Rest Framework associating Related Model with current User

    下一篇: registering a user: difference between UserSerializer.save() and User.objects.create