python - 如何向 django 查询添加静态用户字段

标签 python django django-rest-framework

我需要使用 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 the serializer.

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/

相关文章:

Python 在关闭 GUI 应用程序时意外退出

python - ViewSets 是否在 Django Rest Framework 中生成 view_names?

django - 以编程方式检查syncdb是否正在运行

django - ModelSerializer.update() 和 ModelViewSet.update() 之间的区别

Django-rest-auth 使用 cookie 而不是 Authorization header

python - 从两个 numpy 数组中查找然后排序的更优化方法

python - Python 中的现代、高性能布隆过滤器?

python - python logging.FileHandler 默认使用 block 缓冲吗?

css - 使用 django 加载引导加载程序时出错(未找到 css)

python - 如何在 django-rest-swagger 中指定查询参数序列化程序?