我有一个位置模型,我需要在不指定用户的情况下创建位置,如果用户为空,则用户将被放置在视图集中的request.user中。
这是我的模特:
class Location(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=100)
串行器:
class LocationSerializer(serializers.ModelSerializer):
def is_valid(self):
if not 'user' in self.init_data:
# avoid this validation.. I manage this in the viewset
pass
return not self.errors
class Meta:
model = Location
和viewset
class LocationViewSet(ModelViewSet):
"""
API endpoint that allows location to be created or viewed.
"""
model = Location
serializer_class = LocationSerializer
renderer_classes = (JSONRenderer, JSONPRenderer)
def get_queryset(self):
return self.request.user.locations.filter(deleted=False)
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.DATA, files=request.FILES)
if serializer.is_valid():
self.pre_save(serializer.object)
if not self.object.user:
self.object.user = request.user
self.object = serializer.save(force_insert=True)
self.post_save(self.object, created=True)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED,
headers=headers)
感谢您的任何建议
答案 0 :(得分:2)
您可以在序列化程序中使用required=False
:
class LocationSerializer(serializers.ModelSerializer):
user = serializers.RelatedField(required=False)
修改强>
您还可以使用以下方法简化视图集:
class LocationViewSet(ModelViewSet):
def pre_save(self, obj):
if obj.user_id is None:
obj.user = self.request.user
这可以避免从DRF核心复制代码。