'how to pass query parameters from DRF serializer

when we pass query params through a request to DRF, are query params passed through serializer ? or is there any way to pass them from serializer ?



Solution 1:[1]

As far as I know, there is no way to pass them to the serializer. Query parameters from the request are handled within the view only. An example for filtering a returned queryset using a query parameter would be like:

from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view(['GET'])
def product_list(request):
    qs = Product.objects.all()
    search = request.query_params.get('search')  # Get query parameter
    if search is not None:
        qs = qs.filter(title__icontains=search)
    serializer = ProductSerializer(qs, many=True)
    return Response(serializer.data)

Solution 2:[2]

You can pass additional data when instantiating a serializer in the context argument:

def some_view(self, request):
    serializer = SomeSerializer(data=request.data, 
                                context={"qp": request.query_params.get("qp")})

The context will be accessible in any serializer field method like:

def get_some_field(self, instance):
    qp = self.context["qp"]

Solution 3:[3]

The parameters do not pass throught a Serializer. You need to do it manually.

Here is the example of a DRF view which is generated throught a Serializer which accepts GET-query parameters and return the 200 Response only if query parameters are ok:

from serializers import MySerializer
from rest_framework.viewsets import GenericViewSet
from rest_framework import status
from rest_framework.decorators import action

    
class MyView(GenericViewSet):

    @action(methods=["GET"], detail=False)
    def my_view_endpoint(self, request):
       serializer = MySerializer(data=request.query_params)
       serializer.is_valid(raise_exception=True)
       return Response(status=status.HTTP_200_OK, data=serializer.data)

Solution 4:[4]

Ok, this is one of those architecture issues that may not be all that clear to you.

the "instant" you put in the % and start using server side "directives"?

That code does not run in the front end "just" because you placed it in the markup. That code STILL runs 100% on the server side. And MORE important, while the server is rendering the page, then that code runs. And THEN THE WHOLE page is sent down to the browser side.

As a result?

You actually better off in 99% of cases to write such code in the code-behind. It actually in most cases becomes more diffiuct and more confusing to try and mix in that server side code inside of your markup.

So, now that we cleared up the above?

The first issue is you want a choice 1-5. but, if you chose the 3rd one, then the current 5th or 1st one has to be un-checked, right?

As a result of this common problem, then better off to use a RadioButton list, or a check box list.

Drop in a Say a RadioButton list like this:

        <asp:RadioButtonList ID="RadioButtonList1" runat="server">
        </asp:RadioButtonList>

Now, do we want 5 choices, then use this editor:

enter image description here

(you can hand edit the choices in the markup when you become more comfortable).

So we can type in say 0 - 5 choices

Like this:

enter image description here

Note how I am typing in 5 and "Five" for display. Also, use the property sheet - set the cell spacing (try 10), and set Repeat direction = Horizontal.

You see this markup:

        <asp:RadioButtonList ID="RadioButtonList1" runat="server" CellSpacing="10"
            RepeatDirection="Horizontal">
            <asp:ListItem Value="0">Zero</asp:ListItem>
            <asp:ListItem Value="1">One</asp:ListItem>
            <asp:ListItem Value="2">Two</asp:ListItem>
            <asp:ListItem Value="3">Three</asp:ListItem>
            <asp:ListItem Value="4">Four</asp:ListItem>
            <asp:ListItem Value="5">Five</asp:ListItem>
        </asp:RadioButtonList>

and we run, and see this:

enter image description here

Ok, what about using code to fill out the choices.

Ok, lets try another RadioButtion list like this:

        <asp:RadioButtonList ID="RadioButtonList2" runat="server"
            RepeatDirection="Horizontal">

        </asp:RadioButtonList>

Now what about code? Say I want 1 to 10?

Ok, then we have this code:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            for (int i = 1;i<=10;i++)
            {
                RadioButtonList2.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }
        }
    }

And now we run, and we see this:

enter image description here

And again, REALLY nice since ONLY ONE choice can be picked - we don't have to write any code.

So, it not clear if you want one Radio button list, and 10 choices.

Or, maybe we want to display 10 hotels, and each has a 1-5 rating to display?

Again, we would use say a GridView (for the hotel list), and drop in a RadioButton list as ONE of the columns for the Grid.

And last but not least?

Maybe we want to drive the choices from a data base? Say, a list of Cities.

So, "please pick your favorite city?

Lets drop in a 3rd RB list, and we have this:

        <asp:RadioButtonList ID="RadioButtonList3" runat="server"
            DataTextField="City"
            DataValueField="ID"  >
        </asp:RadioButtonList>

Note how we added to more settings DataValue Field, and Data text field. So, I want to display the City list, but we using a database, and I might want to DISPLAY the text values, but when I pull the choice, I want the database PK row.

So, now my code behind is this:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            for (int i = 1;i<=10;i++)
            {
                RadioButtonList2.Items.Add(new ListItem(i.ToString(), i.ToString()));
            }

            // now load up the city picking Radio button list
            using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
            {
                string strSQL = "SELECT ID, City from City ORDER BY City";
                using (SqlCommand cmdSQL = new SqlCommand(strSQL,conn))
                {
                    conn.Open();
                    RadioButtonList3.DataSource = cmdSQL.ExecuteReader();
                    RadioButtonList3.DataBind();
                }
            }
        }
    }

And now our page looks like this:

enter image description here

So, I hope the above gives you some ideas as to the "general" approach, and the options you have if you want to edit + enter the values, or use some code to fill out the codes, or even use code + database to load up the RadioButton choices.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eyob Tariku
Solution 2
Solution 3 Ivan Saldikov
Solution 4 Albert D. Kallal