1

I want to filter my Django Rest Framework serialized data by the URL provided by user. Here is my code:

models.py:

class Airline(models.Model):
    name = models.CharField(max_length=10, blank=True, null=True)
    code = models.CharField(max_length=2, blank=True, null=True)

    def __str__(self):
        return self.name

class FinancialData(models.Model): 
    airline = models.ForeignKey(Airline)
    mainline_revenue = models.DecimalField(max_digits=7, decimal_places=2)
    regional_revenue = models.DecimalField(max_digits=7, decimal_places=2)
    other_revenue = models.DecimalField(max_digits=7, decimal_places=2)
    total_revenue = models.DecimalField(max_digits=7, decimal_places=2)

        def __str__(self):
        return str(self.mainline_revenue)

view.py:

class ListAirlineFinancialData(generics.ListAPIView):
    serializer_class = FinancialDataSerializer

    def get_queryset(self, *args, **kwargs):
        query_list = FinancialData.objects.filter(pk=airline_id)

urls.py:

urlpatterns = [
    url(r'^api/v1/airline/(?P<pk>\d+)/$', views.ListAirlineFinancialData.as_view(), name='airline_financial_data'),
]

What should I code in views to filter my data for the following URL. http://localhost:8000/api/v1/airline/3/

At this moment Django is giving me an error that name 'airline_id' is not defined I can understand that it wants me to pass on airline_id which is in my database but I really dont know how to do it. What code should I write in views.py that it filters all the data for the airline any particular id. Thanks

1

2 Answers 2

6

Your solution approach is correct. However your code seems ambiguous for readers.

For eg: If you are applying query on FinancialData then your url pattern should have financialdata in urlpath rather than airline. Also <pk> is generally used as primary key for the model you are applying query to and not for the foreign key on the model.

So urlpattern should be like

urlpatterns = [
    url(
        r'^api/v1/financialdata/(?P<airline_pk>\d+)/$',
        views.ListAirlineFinancialData.as_view(),
        name='airline_financial_data'),
]

and url will be like: /api/v1/financialdata/1/

Also, it is a general practice to pass filter parameters as query_params. In that case your urlpattern will be

url(
        r'^api/v1/financialdata/$',
        views.ListAirlineFinancialData.as_view(),
        name='airline_financial_data'),
]

and your url will be like: /api/v1/financialdata/?airline_pk=1

In case of passing filter parameters as query_params, your get_queryset will be a little different:

def get_queryset(self, *args, **kwargs):
    return self.queryset.filter(airline_id=self.request.GET.get('airline_pk'))

Lastly, Django Rest Framework is very powerful yet simple in using. You can read more about filters on Django Rest Framework Filtering

Sign up to request clarification or add additional context in comments.

Comments

1

I have been able to figure out the solution after many hours of research. If anyone else come here for answer then I changed my views to following:

class ListFinancialData(generics.ListAPIView):
    queryset = FinancialData.objects.all()
    serializer_class = FinancialDataSerializer

    def get_queryset(self, *args, **kwargs):
        return self.queryset.filter(airline_id=self.kwargs.get('airline_pk'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.