我首先解释一下我的问题的当前情况。
例如,有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:mUser
到Membership
。Reservation
为1:mMembership
Item
为1:mReservation
class ReservationSerializer(ModelSerializer):
class Meta:
model = Reservation
fields = ('membership', 'item')
从User
自动设置request.user
值的最佳方法是什么,因此ReservationSerializer
所需的属性只是community
和item
代替membership
和item
?
答案 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