Django Rest Framework将相关模型与当前用户相关联
我将首先解释我的问题的当前情况。
楷模
例如有5个模型: 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
是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
所需的属性只是community
和item
而不是membership
和item
?
参考
序列化器的作用是以清晰的方式表示信息,而不是操纵这些数据。 您可能希望在视图上执行此操作:使用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