Django REST Serializer和unique_together和from_native [英] Django REST Serializer and unique_together and from_native

查看:699
本文介绍了Django REST Serializer和unique_together和from_native的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用 SlugRelatedField 来反序列化作为 unique_together 集合的一部分的字段。

I am having trouble using the SlugRelatedField to deserialize a field that is part of unique_together set.

给出一个例子,我有一个博客模型,它有一个标题和一个作者。
这些唯一标识博客的元组(如标题中所指定的作者是唯一的,但不是唯一的网站)。我想从包含这些值的消息中查找博客。

To given an example, I have a Blog model which has a Title and an Author. The tuple of these uniquely identify a Blog (as in the Title is unique to a given Author, but not unique site wide). I want to look up the Blog from a message containing just these values.

为了反序列化消息(即 from_native ), SlugRelatedField 调用: self.queryset.get(** {self.slug_field:data})因为它不是全球唯一的,所以会在标题中失败。这可以通过提供更有限的查询(即只包含博客但是该用户)来解决,但我不知道如何/在哪里是在该字段中设置此查询器的最佳位置(因为我不知道作者直到我得到反序列化该字段)。

In order to deserialize a message (i.e. from_native), the SlugRelatedField calls: self.queryset.get(**{self.slug_field: data}) which will fail on the Title slug because it is not globally unique. This can be solved by providing a more limited queryset (ie one which contains just Blogs but that user), but I am not sure how/where is the best place to set this queryset in the Field (because I do not know the Author until I get to deserializing that field).

一个想法是在get_fields中自己对作者的反序列化,然后我可以过滤Blog的查询。这段代码很丑陋,可能导致作者的两次反序列化,并且当Serializer用于列表视图(而不是详细视图)时有问题。

One idea would be to do my own deserialization of the Author in get_fields where I could then filter the queryset for Blog. This code is pretty ugly, likely results in deserialization of Author twice, and has issues when the Serializer is used for the list view (as opposed to the detail view).

推荐答案

您需要在运行时为您的字段设置QuerySet。

You need to set the QuerySet for your field at runtime.

您可以在序列化器中执行此操作,如: p>

You can do this in the serialiser, something like:

class MyObjectSerializer(serializers.HyperlinkedModelSerializer):
    def get_fields(self, *args, **kwargs):
       fields = super(MyObjectSerializer, self).get_fields(*args, **kwargs)
       fields['slug'].queryset = MyObject.objects.filter(self.context['view'].request.user)
       return fields

或在视图中:

def get_serializer(self):
    serializer = super(MyObjectView, self).get_serializer()
    serializer.fields['slug'].queryset = MyObject.objects.filter(self.request.user)

同样的事情 - 您在对当前用户的引用后,在slug字段上设置QuerySet - 它只取决于哪个最适合您。

It's the same thing — you're setting the QuerySet on the slug field once you have a reference to the current user — it just depends on which is best for you.

我希望有帮助。

这篇关于Django REST Serializer和unique_together和from_native的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆