Skip to content
Advertisement

How can I add the following JSON to a new URL based on its “category”: 2?

I have a JSON array in my server in Django rest framework, but I want to filter them by category , for example some of them have 'category':1 and some of them have 'category':2 like this:

JavaScript

How can I add the following JSON to a new URL based on its "category": 2?

JavaScript

views:

JavaScript

urls:

JavaScript

Advertisement

Answer

Assuming that this thingy you call “json array” is set of database objects you can apply filter as described in drf docs. So in your case it would require to override get_queryset method of ModelViewSet class.

JavaScript

Then, if you hit /product?category=2 it should be filtered. Also, you might want to use django-filters package, but that’s overkill in your case.

Also when you code in Django (or python in general), remember to capitalize every class name so productviewset should be ProductViewSet and so on. I highly encourage to read DRF source code, which is well written and explains a lot of things.

Advertisement