我需要使用 DRF 执行一些特殊的序列化/反序列化,但这些参数所需的参数之一是生成查询的用户。
据我所知,serializers.Field
实例无权访问ViewSet
,因此无权访问ViewSet.request.user
。
所以我想我只需将用户作为静态字段添加到查询集中,以便每个记录都可以访问它。
qry = qry.annotate(user=Value(user, models.ForeignKey(settings.AUTH_USER_MODEL)))
但是,这给了我
ValueError: Related model 'auth.User' cannot be resolved
我也尝试过
q.annotate(user=Value(user, models.ForeignKey(user.__class__)))
但这也异常(exception)。
我到底需要包含哪些内容才能根据需要解决此问题?
最佳答案
看看 CurrentUserDefault
:
A default class that can be used to represent the current user. In order to use this, the
'request'
must have been provided as part of the context dictionary when instantiating theserializer
.owner = serializers.HiddenField( default=serializers.CurrentUserDefault() )
要使用此功能,您需要 pass the request in the context如下:
serializer = AccountSerializer(account, context={'request': request})
关于python - 如何向 django 查询添加静态用户字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37316955/