简体   繁体   English

如何将新字段添加到 drf 查询 output?

[英]How can i add new field into drf query output?

there is get query in Drf get_object Drf get_object 中有 get 查询

query_get = get_object_or_404(My_model, id=1)

i want to add new field in this out put.but do not work.我想在这个输出中添加新字段。但不工作。 when i use当我使用

 query_get['new_field']='1' 

then return that,but can not add new_field in out put.然后返回,但不能在输出中添加 new_field。

If you are using a serializer, you can use it by adding methodfield as follows.如果您使用的是序列化程序,则可以通过添加方法字段来使用它,如下所示。

class MyModelSerializer(ModelSerializer):
    new_field = serializers.SerializerMethodField()

    @staticmethod
    def get_new_field(obj):
        return "1"

get_object_or_404() returns an object, not a queryset. get_object_or_404() 返回 object,而不是查询集。 So in your case it will return an instance of My_model with an id of 1.因此,在您的情况下,它将返回一个 ID 为 1 的 My_model 实例。

The way to pass an extra field to the template depends on whether you're using a class-based or function based view.将额外字段传递给模板的方式取决于您使用的是基于类的视图还是基于 function 的视图。

In case of function-based view:在基于函数的视图的情况下:

query_get = get_object_or_404(My_model, id=1)
context['query_get'] = query_get
context['new_field'] = '1'
return render(request, "my_template.html", context)

With a class based view you can override the get_context_data() method:使用基于 class 的视图,您可以覆盖 get_context_data() 方法:

def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super().get_context_data(**kwargs)
        
        # Add data to the context
        query_get = get_object_or_404(My_model, id=1)
        context['query_get'] = query_get
        context['new_field'] = '1'
        return context

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM