<p>您希望使用序列化程序创建与request.user相关的对象</p>
<p>您在这里需要做的非常简单:</p>
<ol>
<li>重写create()方法</李>
<li>使用序列化程序上下文,从create()方法的视图中获取request.user</李>
</ol>
<pre class="lang-py prettyprint-override"><code># serializers.py
class SensorSerializer(serializers.ModelSerializer):
"""Serializes a sensor object"""
class Meta:
# points serializer to WeatherSensor model
model = models.Sensor
# list fields you want to make accessible from WeatherSensor model in tuple
fields = ('id', 'user_profile', 'name', 'sensor_type', 'surrounding',
'latitude', 'longitude', 'created_at', 'updated_at')
# make foreign key read only by using extra keyword args variable
extra_kwargs = {'user_profile': {'read_only': True}}
def create(self, validated_data):
user = self.context["request"].user
sensor = models.Sensor.objects.create(user_profile=user, **validated_data)
return sensor
# views.py
class SensorListApiView(APIView):
"""Sensor List API View for list and create"""
serializer_class = serializers.SensorSerializer
def post(self, request):
"""Create a weather sensor"""
# self.serializer_class comes with APIView that retrieves serializer class for our review
serializer = self.serializer_class(data=request.data, context={"request":request})
# You need to pass the request in the context.
# etc...
</code></pre>
<p>请小心,因为我在代码中没有看到检查用户是否实际登录的地方</p>